2016-07-27 29 views
4

我正在學習Java8,並期待看到如何將以下內容轉換爲Java8 streaming API,在找到第一個'hit'(如下面的代碼)後,它會'停止'Java8 - 在地圖中搜索值

public int findId(String searchTerm) { 

    for (Integer id : map.keySet()) { 
     if (map.get(id).searchTerm.equalsIgnoreCase(searchTerm)) 
      return id; 
    } 
    return -1; 
} 
+4

當你需要鍵值時,通常最好迭代'entrySet()' –

+1

你的地圖內容是否合理地保持不變?鑰匙是否可以不區分大小寫匹配其他鑰匙? – Bohemian

回答

11

未經測試,這樣的事情應該工作:

return map.entrySet() 
      .stream() 
      .filter(e-> e.getValue().searchTerm.equalsIgnoreCase(searchTerm)) 
      .findFirst() // process the Stream until the first match is found 
      .map(Map.Entry::getKey) // return the key of the matching entry if found 
      .orElse(-1); // return -1 if no match was found 

這是entrySet的流搜索匹配和返回無論是按鍵的組合,如果發現匹配或否則爲-1 。

1

一旦您使用謂詞過濾了流,您需要的是Stream#findFirst()方法。事情是這樣的:

map.entrySet() 
    .stream() 
    .filter(e -> e.getValue().equalsIgnoreCase(searchTerm)) 
    .findFirst(); 

這將返回一個Optional因爲可能沒有過濾後留下的任何元素。

+1

如果沒有匹配,你錯過了返回'-1'。 –

+1

@CrazyNinja是的,這是真的 - 上面的Eran的答案基本上是相同的,但映射到Integer鍵。我認爲在Java 8世界中,您可能會返回比-1更可選的,但這取決於您與客戶端代碼簽訂的任何合同。 – tchambers

+1

@tchambers是的,這真的取決於合同,但OPs合同似乎返回'-1',所以我會堅持。 –