Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) {
    return from + list.subList(from, list.size()).indexOf(item);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading