2014-10-03 104 views
13

我正在尝试使用Java 8流和lambda表达式进行顺序搜索。这里是我的代码使用流API查找列表中项目的所有索引

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)始终打印中第一次出现的索引。我如何打印所有索引?

+0

我不认为你可以用这种结构做。一旦你过滤了,你就失去了索引信息。如果你在这之后做了索引打印,你会得到过滤列表中的索引。 – 2014-10-03 12:38:03

+1

可能的重复http://stackoverflow.com/q/18552005/1407656或http://stackoverflow.com/q/22793006/1407656 – toniedzwiedz 2014-10-03 12:38:14

+0

@Tom在给定的帖子中查询的内容。当我尝试在查询时给出编译错误。 – mallikarjun 2014-10-03 12:49:33

回答

25

一开始,使用Lambda表达式是不是解决所有问题......但是,即使如此,作为一个循环,你会写:

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] 
+0

在printf函数结束时是否有exra%n,提供了三个替代品,但提供了两个参数? – Whome 2014-10-03 12:55:39

+3

@Whome - '%n'增加了一个OS特定的行结束符(一个行为良好的'\ n')。它不需要匹配的替代值。 (请参阅“Line Separator [在文档中]”(http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html)) – rolfl 2014-10-03 12:58:47

相关问题