The flatMap function is very similar to the map function, but it is used when the operation might return more than one value and we want to keep a stream of single elements. In the case of map, a stream of collections would be returned instead. Let's see flatMap in use:
@Test
public void gettingLettersUsedInNames() {
List<String> names = Arrays.asList("Alex", "Paul", "Viktor");
List<String> lettersUsed = Collections.emptyList();
assertThat(lettersUsed)
.hasSize(12)
.containsExactly("a","l","e","x","p","u","v","i","k","t","o","r");
}
One possible solution could be:
List<String> lettersUsed = names.stream()
.map(String::toLowerCase)
.flatMap(name -> Stream.of(name.split("")))
.distinct()
.collect(Collectors.toList());
This time we have used Stream.of(), a convenient method for creating Streams. Another really nice feature is the method distinct(), which returns a collection of unique elements, comparing them using the method equals().