Java 使用流 API 在列表中查找项目的所有索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26179001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find all the indexes of an item within a list using stream API
提问by mallikarjun
I am trying sequential search using Java 8 streams and lambda expressions. Here is my code
我正在尝试使用 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
I know list.indexOf(e)
always prints the index of the first occurrence. How do I print all the indexes?
我知道list.indexOf(e)
总是打印第一次出现的索引。如何打印所有索引?
采纳答案by rolfl
For a start, using Lambdas is not the solution to all problems... but, even then, as a for loop, you would write it:
首先,使用 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);
}
}
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'.
现在,这并没有什么特别的错误,但请注意,这里的关键方面是索引,而不是值。索引是“循环”的输入和输出。
As a stream::
作为一个流::
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));
Produces output:
产生输出:
Found 16 at indices [2, 5]