如何在没有循环的列表中查找对象的所有索引?

Xii*_*ref 1 java

我有一个可能很简单的问题,但是我找不到答案。

我希望能够获取对象在列表中出现的所有索引,但无需在列表上循环。

public void exampleFunction(){
    ArrayList<Integer> completeList = new ArrayList<>();
    completeList.add(1);
    completeList.add(2);
    completeList.add(1);

    Integer searchObject = 1;
    List<Integer> indexes = DO SOMETHING TO GET THE INDEXES LIST [0, 2];
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 6

您可以Stream通过创建IntStream具有的所有索引的来使用API,completeList然后过滤掉1找不到索引的索引:

List<Integer> indexList = IntStream.range(0, completeList.size())
                                   .filter(x -> completeList.get(x) == 1)
                                   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)