使用流 API 查找列表中某个项目的所有索引

2022-09-03 00:32:43

我正在尝试使用Java 8流和lambda表达式进行顺序搜索。这是我的代码

List<Integer> list = Arrays.asList(10, 6, 16, 46, 5, 16, 7);
int search = 16;
list.stream().filter(p -> p == search).forEachOrdered(e -> System.out.println(list.indexOf(e)));
Output: 2
        2

我知道总是打印第一次出现的索引。如何打印所有索引?list.indexOf(e)


答案 1

首先,使用Lambdas并不是所有问题的解决方案...但是,即使这样,作为一个for循环,你也会写它:

List<Integer> results = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
    if (search == list.get(i).intValue()) {
        // found value at index i
        results.add(i);
    }
}

现在,这没有什么特别的错误,但请注意,这里的关键方面是指数,而不是值。索引是“循环”的输入和输出。

作为流::

List<Integer> list = Arrays.asList(10, 6, 16, 46, 5, 16, 7);
int search = 16;
int[] indices = IntStream.range(0, list.size())
                .filter(i -> list.get(i) == search)
                .toArray();
System.out.printf("Found %d at indices %s%n", search, Arrays.toString(indices));

产生输出:

Found 16 at indices [2, 5]

答案 2

要将 a 中每个值的索引查找为 ,我们可以将索引的 IntStreamCollectors.groupingBy 结合使用ListMap

import java.util.stream.Collectors;
import java.util.stream.IntStream;
//...
final Map<Integer, List<Integer>> indexMap = IntStream.range(0, list.size()).boxed()
        .collect(Collectors.groupingBy(list::get));
//{16=[2, 5], 5=[4], 6=[1], 7=[6], 10=[0], 46=[3]}
//Map of item value to List of indices at which it occurs in the original List

Demo

现在,如果要获取 的索引列表,可以按如下方式执行此操作:search

System.out.println(indexMap.get(search));