Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What can be the way to achieve it in Java 8.

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading