Trying to find all occurrences of an object in Arraylist, in java

missrg picture missrg · Dec 16, 2012 · Viewed 40.1k times · Source

I have an ArrayList in Java, and I need to find all occurrences of a specific object in it. The method ArrayList.indexOf(Object) just finds one occurrence, so it seems that I need something else.

Answer

André C. Andersen picture André C. Andersen · Dec 16, 2012

I don't think you need to be too fancy about it. The following should work fine:

static <T> List<Integer> indexOfAll(T obj, List<T> list) {
    final List<Integer> indexList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        if (obj.equals(list.get(i))) {
            indexList.add(i);
        }
    }
    return indexList;
}