Java Reference
In-Depth Information
enable efficient operations, parallel streams let you use the nonthread-safe collections safely,
as long as you do not modify the collection while you are operating on it .
To use a parallel stream, you just ask the collection for it, using parallelStream() instead
of the stream() method we used in Simplifying Processing with Streams .
For example, suppose that our camera business takes off, and we need to find cameras by
type and price range quickly (and with less code than we used before):
public
public static
static void
void main ( String [] args ) {
for
for ( Object camera : privateListOfCameras . parallelStream ().
filter ( c -> c . isIlc () && c . getPrice () < 500 ).
toArray ()) {
System . out . println ( camera );
}
}
Create a parallel stream from the List of Camera objects. The end result of the stream
will be iterated over by the foreach loop.
Filter the cameras on price, using the same Predicate lambda that we used in Using
Lambdas/Closures Instead of Inner Classes .
Terminate the Stream by converting it to an array.
Th e body of the foreach loop: print one Camera from the stream.
WARNING
This is only reliable as long as no thread is modifying the data at the same time as the
searching is going on. See the thread interlocking mechanisms in Chapter 22 to see how
to ensure this.
 
 
 
 
 
 
Search WWH ::




Custom Search