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

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

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

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.

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