flatMap

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:

@Testpublic 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 ...

Get Test-Driven Java Development - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.