试图在java中查找Arraylist中出现的所有对象

我在Java中有一个ArrayList,我需要在其中查找所有出现的特定对象。 方法ArrayList.indexOf(Object)只找到一个匹配项,所以我似乎需要其他东西。

我认为你不需要过于花哨。 以下应该可以正常工作:

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

我想你需要得到ArrayList的所有索引,其中该槽上的对象与给定对象相同。

以下方法可能会执行您希望它执行的操作:

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

它使用equals方法搜索对象,并将当前数组索引保存到带索引的列表中。 您在问题中指的是indexOf ,它使用equals方法来测试相等性,如Java文档中所述:

搜索给定参数的第一次出现,使用equals方法测试equals

迭代所有元素,不要破坏循环

ArrayList每个元素与您的object进行比较( arrayList.get(i).equals(yourObject)

如果匹配比索引(i)应该存储到单独的ArrayList(arraListMatchingIndexes)中。

有时这样我做“全部删除”,当我也需要这些职位时。

我希望它有所帮助!

 for (int i=0; i 

希望这可以帮助。

这与此答案类似,只是使用stream API。

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