reduce

In the previous example, the function returns the list of letters used in all the names passed as input. But if we are only interested in the number of different letters, there's an easier way to proceed. reduce basically applies a function to all elements and combines them into one single result. Let's see an example:

@Testpublic void countingLettersUsedInNames() {  List<String> names = Arrays.asList("Alex", "Paul", "Viktor");  long count = 0;  assertThat(count).isEqualTo(12);}

This solution is very similar to the one we used for the previous exercise:

long count = names.stream()  .map(String::toLowerCase)  .flatMap(name -> Stream.of(name.split("")))  .distinct()  .mapToLong(l -> 1L)  .reduce(0L, (v1, v2) -> v1 + v2);

Even though the preceding ...

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.