Java Reference
In-Depth Information
if (anyMale.isPresent()) {
System.out.println("Any male: " + anyMale.get());
}
else {
System.out.println("No male found.");
}
// Find the first male
Optional<Person> firstMale = persons.stream()
.filter(Person::isMale)
.findFirst();
if (firstMale.isPresent()) {
System.out.println("First male: " + anyMale.get());
}
else {
System.out.println("No male found.");
}
}
}
All males: false
Anyone born in 1970: true
Anyone born in 1955: false
Any male: (1, Ken, MALE, 1970-05-04, 6000.00)
First male: (1, Ken, MALE, 1970-05-04, 6000.00)
Parallel Streams
Streams can be sequential or parallel. Operations on a sequential stream are processed in serial using one thread.
Operations on a parallel stream are processed in parallel using multiple threads. You do not need to take additional
steps to process streams because they are sequential or parallel. All you need to do is call the appropriate method that
produces sequential or parallel stream. Everything else is taken care of by the Streams API. This is why I stated in the
beginning of this chapter that you get parallelism in stream processing “almost” for free.
Most of the methods in the Streams API produce sequential streams by default. To produce a parallel stream
from a collection such as a List or a Set , you need to call the parallelStream() method of the Collection interface.
Use the parallel() method on a stream to convert a sequential stream into a parallel stream. Conversely, use the
sequential() method on a stream to convert a parallel stream into a sequential stream.
The following snippet of code shows serial processing of the stream pipeline because the stream is sequential:
String names = Person.persons() // The data source
.stream() // Produces a sequential stream
.filter(Person::isMale) // Processed in serial
.map(Person::getName) // Processed in serial
.collect(Collectors.joining(", ")); // Processed in serial
 
Search WWH ::




Custom Search