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

时间:2019-06-20 09:16:50

标签: 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];
}

1 个答案:

答案 0 :(得分:6)

您可以使用Stream API,方法是创建一个具有IntStream的所有索引的completeList,然后过滤掉未找到1的索引:

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