O'Reilly logo

Test-Driven Java Development - Second Edition by Viktor Farcic, Alex Garcia

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required