Java Reference
In-Depth Information
public static void main(String[] args) {
// Perform the stream processing
List<Integer> list = new CopyOnWriteArrayList<>();
generateParallelStream().forEach(list::add);
}
}
Note that if the collection you want to add elements to is not thread-safe, and your stream is a parallel
stream, then you can use a Collection.synchronizedList(List) (or related method) to synchronize it.
This can be done inline, which would create a line like this:
generateParallelStream().forEach(Collections.synchronizedList(list)::add);
If you want your stream to produce an immutable list or set, then the simplest approach is to use
Google's Guava library. Among other immutable types, the Guava library provides an ImmutableList and
ImmutableSet (among other immutable types), and it provides builder types for each of these immutable
types. The add method for these builder types works just as well as the add method of the list that we saw
before. These builders are also all thread-safe, so they are safe to use with parallel streams. An example of
this usage is given in Listing 7-9. This approach works particularly well if you simply build up your collection
within one method and then return it to the user as your final step.
Listing 7-9. Bridging Streams to Collections Using a Builder
import com.google.common.collect.ImmutableList;
import java.util.*;
import java.util.stream.*;
public class Listing9 {
public static Stream<Integer> generateParallelStream() {
final int elements = 1000;
List<Integer> toReturn = new ArrayList<>(elements);
for (int i = 0; i < elements; i++) {
toReturn.add(i);
}
return toReturn.parallelStream();
}
public static void main(String[] args) {
// Perform the stream processing
ImmutableList.Builder<Integer> builder = ImmutableList.builder();
generateParallelStream().forEach(builder::add);
ImmutableList list = builder.build();
}
}
 
Search WWH ::




Custom Search