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?
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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With