使用流API查找列表中项目的所有索引 [英] Find all the indexes of an item within a list using stream API

查看:78
本文介绍了使用流API查找列表中项目的所有索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying sequential search using Java 8 streams and lambda expressions. Here is my code

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)始终打印第一个匹配项的索引。如何打印所有索引?

I know list.indexOf(e) always prints the index of the first occurrence. How do I print all the indexes?

推荐答案

首先,使用Lambdas并不能解决所有问题......但是即便如此,作为for循环,你会写它:

For a start, using Lambdas is not the solution to all problems... but, even then, as a for loop, you would write it:

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

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

Now, there's nothing particularly wrong with that, but note that the critical aspect here is the index, not the value. The index is the input, and the output of the 'loop'.

作为流::

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]

这篇关于使用流API查找列表中项目的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆