Java 8 – get all unique characters from List of string using flatmap

Let’s see how we can get all the unique characters from List of Strings.

Suppose we have the following input List:

{"Berlin", "Paris", "Madrid"}

desired output:

{"B", "e", "r", "l", "i", "n", "P", "a", "s", "M", "d"}

One might think that it can be done by just mapping each string into characters and then make a distinct.

cities.stream()
      .map(c->c.split(""))
      .distinct()
      .collect(Collectors.toList());

This solution has a problem since the output of map function is Stream<String[]>, but what we need is Stream<String>, since we want to have Stream of characters and not stream of arrays.
We need to do two things to make it work:

  1. Convert String[] into Stream<String>. This is done by Arrays.stream().
  2. 1st step alone is not enough, because for each character of array we will have its own stream and we will end up  with Stream<Stream<String>>. The solution for this problem is to use flatMap function, which will                    concatenate all the separated streams outputted by Arrays.stream() into one stream:
List uniqueChars = cities.stream()
        .map(c -> c.split(""))
        .flatMap(Arrays::stream)
        .distinct()
        .collect(Collectors.toList());

for (String element: uniqueChars) {
            System.out.print(element+" ");
}

//output
B e r l i n P a s M d