How to stream a map with a values Stream<String> using Stream API?

I have the map Map<String, Stream<String>>. I need to build sorted stream of all participants without duplication (ignore null or empty strings, extra spaces and case sensitivity).

For example, for a given map
{"A"=["B", "C", " D "], "B"=["kas", "B", "c ", "dddd"]}

I should get
["B", "C", "D", "Dddd", "Kas"]

I need to create method like that, but I don’t even know how to start. Will be thankful for any advice!

public Stream<String> listN(Map<String, Stream<String>> map) {
      map.values().stream()
    }

>Solution :

Stream the map’s values, flapMap to stream of Strings, then apply the various filters and modifications, distinct, sort:

public Stream<String> listN(Map<String, Stream<String>> map) {
    return map.values().stream()
      .flatMap(s -> s)
      .filter(s -> s != null && !s.isEmpty())
      .map(String::trim)
      .map(String::toLowerCase)
      .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
      .distinct()
      .sorted();
}

See live demo.

Leave a Reply