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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With