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

Deadly 提交于 2019-11-26 11:25:54

问题


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.


回答1:


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



回答2:


I suppose you need to get all indices of the ArrayList where the object on that slot is the same as the given object.

The following method might do what you want it to do:

public static <T> int[] indexOfMultiple(ArrayList<T> list, T object) {
    ArrayList<Integer> indices = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).equals(object)) {
            indices.add(i);
        }
    }
    // ArrayList<Integer> to int[] conversion
    int[] result = new int[indices.size()];
    for (int i = 0; i < indices.size(); i++) {
        result[i] = indices.get(i);
    }
    return result;
}

It searches for the object using the equals method, and saves the current array index to the list with indices. You're referring to indexOf in your question, which uses the equals method to test for equality, as said in the Java documentation:

Searches for the first occurence of the given argument, testing for equality using the equals method.




回答3:


iterate over all elements, don't break the loop

each element of the ArrayList compare with your object ( arrayList.get(i).equals(yourObject) )

if match than the index ( i ) should be stored into a separate ArrayList ( arraListMatchingIndexes).

Sometimes in this way I do a "remove all", when I need the positions too.

I hope it helps!




回答4:


Do

for (int i=0; i<arrList.size(); i++){
    if (arrList.get(i).equals(obj)){
        // It's an occurance, add to another list
    }
}

Hope this helps.




回答5:


This is similar to this answer, just uses stream API instead.

List<String> words = Arrays.asList("lorem","ipsum","lorem","amet","lorem");
String str = "lorem";
List<Integer> allIndexes =
        IntStream.range(0, words.size()).boxed()
                .filter(i -> words.get(i).equals(str))
                .collect(Collectors.toList());
System.out.println(allIndexes); // [0,2,4]


来源:https://stackoverflow.com/questions/13900585/trying-to-find-all-occurrences-of-an-object-in-arraylist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!