How to find an index of the ArrayList from the starting index in Java?

111 Views Asked by At

I want to search for an index of the element in the ArrayList but I want to start searching from starting index different than 0.

I tried like this:

import java.util.*;

public class Test{
    public static void main(String[] args) {
        ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB","CCCC","DDDD"));
        System.out.println(bricks.subList(1, bricks.size()).indexOf("CCCC"));
    }
}

Output:

0

Expected output:

1

I want to start searching for "CCCC" in "bricks" from the starting index "1" not from "0"

3

There are 3 best solutions below

3
Bohemian On BEST ANSWER

Your code finds the index within the sublist.

To find the index within the original list, add the index used to create the sublist to the result:

System.out.println(bricks.subList(1, bricks.size()).indexOf("CCCC") + 1);

Some refactoring makes this clearer:

public static <T> int indexOfAfter(List<T> list, T item, int from) {
    int result = list.subList(from, list.size()).indexOf(item);
    return result == -1 ? -1 : (from + result);
}
0
Ser On
import java.util.*;

public class Test{
    public static void main(String[] args) {
        int startIndex = 1;
        ArrayList<String> bricks = new ArrayList<String>(List.of("BBBB","CCCC","DDDD"));
        int index = bricks.subList(startIndex, bricks.size()).indexOf("CCCC");
        if(index != -1){
            index = index + startIndex;
        }
        System.out.println(index);
    }
}
0
shmosel On

You could write your own helper:

static <T> int indexOf(List<T> list, int offset, T element) {
    for (int i = offset; i < list.size(); i++) {
        if (Objects.equals(list.get(i), element)) {
            return i;
        }
    }
    return -1;
}

Note that this may be inefficient for non-random-access lists like LinkedList. It also handles the lower bound differently from the upper bound, but that can be fixed with an additional check.