user2691659
user2691659

Reputation:

Break Loop After First Iteration

I have a List that contains many rows of data.What i want to do is return only the first iterated value and nothing else.

public int getnumber() {    
    for (Bike temp : bikes) {
        return temp.getBikeID();
        break;
    }
}

I tried something like the above..but the break statement is unreachable. How may i achieve this ?

I know that i could still just declare a variable outside of the loop then assign the value in the loop but the returned value will be the last row.

Upvotes: 0

Views: 3937

Answers (5)

ifloop
ifloop

Reputation: 8386

You can access you list's indices via .get() directly. No need for an iteration if you only need one or a hand full of specific elements:

public int getnumber() {
    int result = 0;

    if (bikes != null && bikes.size() > 0)
        result = bikes.get(0).getBikeID();

    return result;
}

Or even shorter, with the use of the ternary operator (condition ? true : false;):

public int getnumber() {
    return (bikes != null && bikes.size() > 0) ? bikes.get(0).getBikeId() : 0;
}

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 12880

This is because of the return statement before break. The return statement will take the execution to the calling method. so, the break statement is unreachable.

You don't need to iterate to get the first value of the collection. The first index would be 0. so, just make it

if(bikes!=null && bikes.size() > 0)
return bikes.get(0).getBikeId();
return -1; // `-1` denotes failure or put anything relevant to failure

Upvotes: 4

Marko Topolnik
Marko Topolnik

Reputation: 200168

Simply delete the break statement. In fact, this is all you need:

for (Bike temp : bikes) return temp.getBikeID();
return -1;

In place of return -1 put the behavior you prefer for the "not found" case.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try like this -

// null and size check to make sure if there is something on 0 index
return bikes != null && bikes.size > 0 ? bikes.get(0).getBikeId() : 0;

Upvotes: 2

Thomas
Thomas

Reputation: 1420

Do not loop and try directly :

 return bikes.get(0).getBikeId();

Upvotes: 3

Related Questions