Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten map values using java streams

I am new to Java streams and have a problem at hand. I have a map like this:

Map<String, List<String>> specialProductsMap

And i want to flatten the map values to a set which contains all the String values in lists in the specialProductsMap. How can i do this using Java Streams?

like image 939
Shruti Seth Avatar asked Sep 02 '25 14:09

Shruti Seth


2 Answers

You may use the flatMap operator to get this thing done. Here's how it looks.

Set<String> valueSet = specialProductsMap.values().stream()
    .flatMap(List::stream)
    .collect(Collectors.toSet());
like image 187
Ravindra Ranwala Avatar answered Sep 05 '25 03:09

Ravindra Ranwala


First Obtain the list of values from map then use stream api like this

Set<String> setOfString = specialProductsMap.values().stream().flatMap(list->list.stream())
            .collect(Collectors.toSet());

Or Like this Using Method reference

Set<String> setOfString = specialProductsMap.values().stream().flatMap(List::stream)
            .collect(Collectors.toSet());
like image 36
Rahil Husain Avatar answered Sep 05 '25 04:09

Rahil Husain