2014-10-03 85 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