Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 276
missrg Avatar asked Dec 16 '12 10:12

missrg


People also ask

How do you count elements in an ArrayList?

The size of an ArrayList can be obtained by using the java. util. ArrayList. size() method as it returns the number of elements in the ArrayList i.e. the size.


1 Answers

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;
}
like image 52
André C. Andersen Avatar answered Oct 16 '22 06:10

André C. Andersen