简体   繁体   English

使用 Java 8 从 List 的 Map 中获取基于其大小的列表

[英]Get the list based on its size from a Map of List using Java 8

I have a Map<String, List<String>> .我有一个Map<String, List<String>> I am trying to retrieve all the List<String> from the map which has size > 1 and collect them to a new list.我正在尝试从大小 > 1 的 map 中检索所有List<String>并将它们收集到新列表中。

Trying to find out a way to do it in Java 8.试图在 Java 中找到一种方法 8。

Below is how I tried to implement the code but I get a List<String, List<String>>下面是我如何尝试实现代码,但我得到了一个List<String, List<String>>

map.entrySet().stream()
   .filter(e->e.getValue().size()>1)
   .collect(Collectors.toList())

What can be the way to achieve it in Java 8. Java有什么办法可以实现 8.

You are streaming over the entries (key-value pairs), not the values themselves, hence the unexpected result.您流过条目(键值对),而不是值本身,因此出现了意外结果。 If you instead stream over the values (since it seems like you don't care about the keys), you get the desired output:如果您改为 stream 而不是值(因为看起来您不关心键),您将获得所需的 output:

map.values().stream()
   .filter(e->e.size()>1)
   .collect(Collectors.toList())

Edit: This is assuming that the desired outcome is List<List<String>> , that is the list of all lists with a size greater than 1.编辑:这是假设所需的结果是List<List<String>> ,即大小大于 1 的所有列表的列表。

If you instead want to collapse all those values into a single List<String> , you'd use flatMap to collapse them:如果你想将所有这些值折叠成一个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM