Java Reference
In-Depth Information
filter(e)
e1
e1
e2
X
e3
X
en
en
Input stream
Filtered stream
Figure 13-9. A pictorial view of the filter operation
You can apply a filter operation to a stream using the filter() method of the Stream , IntStream , LongStream ,
and DoubleStream interfaces. The method accepts an instance of the Predicate interface.
In a map operation, the new stream contains the same number of elements with different values from the
input stream. In a filter operation, the new stream contains a different number of elements with the same values from
the input stream.
Tip
The following snippet of code uses a stream of people and filters in only females. It maps the females to their
names and prints them on the standard output.
Person.persons()
.stream()
.filter(Person::isFemale)
.map(Person::getName)
.forEach(System.out::println);
Donna
Laynie
The following snippet of code applies two filter operations to print the names of all males having income more
than 5000.0:
Person.persons()
.stream()
.filter(Person::isMale)
.filter(p -> p.getIncome() > 5000.0)
.map(Person::getName)
.forEach(System.out::println);
Ken
Jeff
 
Search WWH ::




Custom Search