Java Reference
In-Depth Information
Optional<T> findAny()
•
Optional<T> findFirst()
•
The primitive type streams such as
IntStream
,
LongStream
, and
DoubleStream
also contain the same methods
that work with a predicate and an optional one for primitive types. For example, the
allMatch()
method in the
IntStream
takes an
IntPredicate
as an argument and the
findAny()
method returns an
OptionalInt
.
All find and match operations are terminal operations. They are also short-circuiting operations. A short-circuiting
operation may not have to process the entire stream to return the result. For example, the
allMatch()
method checks
if the specified predicate is true for all elements in the stream. It is sufficient for this method to return false if the
predicate evaluates to false for one element. Once the predicate evaluates to false for one element, it stops further
processing (short-circuits) of elements and returns the result as false. The same argument goes for all other methods.
Note that the return type of the
findAny()
and
findFirst()
methods is
Optional<T>
because these methods may not
have a result if the stream is empty.
The program in Listing 13-14 shows how to perform find and match operations on streams. The program uses
sequential stream because the stream size is very small. Consider using a parallel stream if the match has to be performed
on large streams. In that case, any thread can find a match or not find a match to end the matching operations.
Listing 13-14.
Performing Find and Match Operations on Streams
// FindAndMatch.java
package com.jdojo.streams;
import java.util.List;
import java.util.Optional;
public class FindAndMatch {
public static void main(String[] args) {
// Get the list of persons
List<Person> persons = Person.persons();
// Check if all persons are males
boolean allMales = persons.stream()
.allMatch(Person::isMale);
System.out.println("All males: " + allMales);
// Check if any person was born in 1970
boolean anyoneBornIn1970 =
persons.stream()
.anyMatch(p -> p.getDob().getYear() == 1970);
System.out.println("Anyone born in 1970: " + anyoneBornIn1970);
// Check if any person was born in 1955
boolean anyoneBornIn1955 =
persons.stream()
.anyMatch(p -> p.getDob().getYear() == 1955);
System.out.println("Anyone born in 1955: " +
anyoneBornIn1955);
// Find any male
Optional<Person> anyMale = persons.stream()
.filter(Person::isMale)
.findAny();