September 2019
Intermediate to advanced
816 pages
18h 47m
English
In Chapter 8, Functional Style Programming – Fundamentals and Design Patterns, in the Writing functional interfaces section, we defined a filter() method based on a functional interface named Predicate. The Java Stream API already has such a method, and the functional interface is called java.util.function.Predicate.
Let's assume that we have the following List of integers:
List<Integer> ints = Arrays.asList(1, 2, -4, 0, 2, 0, -1, 14, 0, -1);
Streaming this list and extracting only non-zero elements can be accomplished as follows:
List<Integer> result = ints.stream() .filter(i -> i != 0) .collect(Collectors.toList());
The resulting list will contain the following elements: 1, 2, -4, 2, -1, ...