[英]Get the list based on its size from a Map of List using Java 8
我有一個Map<String, List<String>>
。 我正在嘗試從大小 > 1 的 map 中檢索所有List<String>
並將它們收集到新列表中。
試圖在 Java 中找到一種方法 8。
下面是我如何嘗試實現代碼,但我得到了一個List<String, List<String>>
map.entrySet().stream()
.filter(e->e.getValue().size()>1)
.collect(Collectors.toList())
Java有什么辦法可以實現 8.
您流過條目(鍵值對),而不是值本身,因此出現了意外結果。 如果您改為 stream 而不是值(因為看起來您不關心鍵),您將獲得所需的 output:
map.values().stream()
.filter(e->e.size()>1)
.collect(Collectors.toList())
編輯:這是假設所需的結果是List<List<String>>
,即大小大於 1 的所有列表的列表。
如果你想將所有這些值折疊成一個List<String>
,你可以使用flatMap
來折疊它們:
map.values().stream()
.filter(e->e.size()>1)
.flatMap(List::stream)
.collect(Collectors.toList())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.