Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip if-statement once condition is met

Tags:

java

loops

This question comes from my OCD-ish nature. Say i have this piece of code.

boolean executed = false;
for(Object o : Collection){
    if((o fulfills condition) && executed  == false){
        //do something
        executed  = true;
    } 
    //other code
}

If the specification only requires that the if statement executes once, is there a better way to skip checking the if conditional than setting executed to true? It bothers me that the loop needs to check the if conditional every single loop iteration, after the if statement has already been executed.

The point of the executed boolean is to prevent the if statement from executing again. I'm not sure this is possible, but i want to take it one step further, and skip checking the if conditional once executed is true.

EDIT: I still need to finish the loop after the condition is met.

like image 617
Eric Guan Avatar asked Aug 26 '15 23:08

Eric Guan


2 Answers

Not really; you're stuck checking that conditional each time with this code flow. There are ways to make it less expensive, though.

I would advise against using continue, since it will cause you to check the conditional repeatedly and then fall through, which probably isn't what you want.

The simplest thing to do may be to reorder the boolean AND statement.

boolean executed = false;
for(Object o : Collection){
    if(!executed && (o fulfills condition)){
        executed  = true;
    } 
    //other code
}

Due to Java's short-circuit nature, you will only ever check !executed, and on its second and future runs, that will evaluate to false, thus "skipping" the conditional check.

like image 175
Makoto Avatar answered Sep 19 '22 09:09

Makoto


i would go with a different way, like below:

int i = 0;
for ( ; i<collection.size() ; i++)
{
    Object o = collection.get(i);
    if (o fulfills condition)
    {
        // do what you gotta do and then
        break;
    }
    doSomethingElse(o); // define a private method for whatever is done here
}
for ( ; i<collection.size() ; i++)
{
    doSomethingElse(collection.get(i));
}
like image 29
tt_emrah Avatar answered Sep 18 '22 09:09

tt_emrah