简体   繁体   中英

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

I have a 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.

Trying to find out a way to do it in Java 8.

Below is how I tried to implement the code but I get a 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.

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:

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.

If you instead want to collapse all those values into a single List<String> , you'd use flatMap to collapse them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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