jiji
jiji

Reputation: 347

Return an element of a for-loop outside the for-loop

How can I do to return an element of a for-loop?

private List<String> list = new ArrayList<String>();
//we only neeed one good element of the list
    String find(){
        for (int i=0; i<list.size(); i++){
            if (list.get(i).isGood()) {
                return list.get(i);
            }
        }
   return list.get(i); //doesn't work obviously, but how to make it work?
}

It doesn't compile because there is no return statement. I would like to return list.get(i).

Upvotes: 0

Views: 894

Answers (4)

Sergei Rybalkin
Sergei Rybalkin

Reputation: 3453

break; call is unreachable code statement. Any code brunch should have return statement. With Stream API:

String find() {
    return list.stream()
               .filter(Clazz::isGood)
               .findFirst()
               .get();
}

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

When a return instruction is reached the code exit immediately from the current function, so any following line is not accepted because will never be reached.

Upvotes: 0

fabian
fabian

Reputation: 82461

Calling break after a return call is unnecessary, since the method is exited after the return statement. Therefore the break statement has no chance of ever being executed which is why this code doesn't compile.

Furthermore you need a return or throw statement after the loop in case no value is returned form the loop, e.g.:

String find(){
   for (int i=0; i<list.size(); i++){
        if (list.get(i).isGood()) {
            return list.get(i);
        }
    }
    return null;
}

Upvotes: 3

Shahid
Shahid

Reputation: 2330

You don't have to break as you have called return. It exits the method from the line where return is called. So you don't have to think to break the loop.

Learn more about return.

Upvotes: 0

Related Questions