Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search a java.util.List starting at a specific index

Is there a built-in method to search a java.util.List specifying the first item to start the search from? Like you can do with Strings

I know I can easily implement something on my own, but I'd rather not reinvent the wheel if Java or http://commons.apache.org/collections/api-release/org/apache/commons/collections/package-summary.html already has it.

I'm not asking how to implement this, I'm asking whether something is already available A lot of the suggestions here were buggy.

If anybody cares for receiving credit for the right answer, please update your answer to say that there is not a built-in way to do it (if you know for sure)

Here's what I would like to do

List<String> strings = new ArrayList<String>();
// Add some values to the list here
// Search starting from the 6th item in the list
strings.indexOf("someValue", 5);

Right now I'm using

/**
 * This is like List.indexOf(), except that it allows you to specify the index to start the search from
 */
public static int indexOf(List<?> list, Object toFind, int startingIndex) {
    for (int index = startingIndex; index < list.size(); index++) {
        Object current = list.get(index);
        if (current != null && current.equals(toFind)) {
            return index;
        }
    }
    return -1;
}

And I've also implemented it as

public static int indexOf(List<?> list, Object toFind, int startingIndex) {
    int index = list.subList(startingIndex).indexOf(toFind);
    return index == -1 ? index : index + startingIndex;
}
like image 396
Juan Mendes Avatar asked Nov 29 '25 23:11

Juan Mendes


1 Answers

No not a single method, but there is a simple documented way of doing this with 1-2 lines of code. It even says so in the documentation for this method:

strings.subList(5, strings.size()).indexOf("someValue");

Possibly add 5 to the result (if not -1), depending on if you want to keep that sublist around or not etc:

int result = list.subList(startIndex, list.size()).indexOf(someValue);
return result== -1 ? -1 : result+startIndex;

Note: subList does not create a new List, just a view into the original one.

like image 145
Mattias Isegran Bergander Avatar answered Dec 01 '25 13:12

Mattias Isegran Bergander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!