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:

@Test
public 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 code snippet solves the problem, there is a much nicer way to do it:

long count = names.stream()
.map(String::toLowerCase)
.flatMap(name -> Stream.of(name.split("")))
.distinct()
.count();

The function count() is another built-in tool that Streams includes. It's a particular shortcut for a reduction function that counts the number of elements the stream contains.

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.164.143