Exit a loop when it finds a Java environment

1

I have the following function that searches the entire list and when it finds the occurrence, it returns it at the end.

private static int getIndexRouteInListByRef(List<Route> mArray, String search) {

    int outIndex = -1;
    for (int i = 0; i < mArray.size(); i++) {
        if (mArray.get(i).getRef().equals(search)) {
            outIndex = i;
        }
    }

    return outIndex;

}

How could it be optimized so that when it finds the occurrence, leave the loop and return the index?

    
asked by Webserveis 11.12.2016 в 14:18
source

2 answers

5

break; It's what you need to exit any loop declaration as for, while o do-while .

In your case, it's going to be something like this: -

private static int getIndexRouteInListByRef(List<Route> mArray, String search) {
        int index = -1;
        for (int i = 0; i < mArray.size(); i++) {
            if (mArray.get(i).getRef().equals(search)) {
                index = i;
                break;

            }

        }
        return index;
    }

And if you think it's a bad practice to use the break; I leave a response from the community in English that is very useful and clear, I know you should provide a link with information in Spanish but you can use the translator if necessary. link

    
answered by 11.12.2016 / 15:51
source
4

In this case, you can make a return within the loop. In fact, doing so, you do not even need to define a variable outIndex :

private static int getIndexRouteInListByRef(List<Route> mArray, String search) {

    for (int i = 0; i < mArray.size(); i++) {
        if (mArray.get(i).getRef().equals(search)) {
            return i;
        }
    }

    return -1;
}
    
answered by 11.12.2016 в 14:23