javaarraylistindexof

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


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"


Solution

  • 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);
    }