How to flatten map values using java streams

Shruti Seth :

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?

Ravindra Ranwala :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125740&siteId=1