Java Reference
In-Depth Information
Listing 7-7. Bridging Streams to Collections via toArray()
import java.util.*;
import java.util.stream.*;
public class Listing7 {
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
List<Object> list = Arrays.asList(generateParallelStream().toArray());
}
}
If you have some existing list that you want to add an element into, then you can simply use the
List.add method as your consumer. That method technically returns boolean , and so it is not precisely the
accurate shape for the Consumer , but Java will allow you to bend the rules here. If you have a list that exists
before your stream operations, then simply pass that list's list::add method into the stream's forEach , and
you are fine. A similar approach will work for adding stream elements to an existing set. The only caveat
is that if you are using a parallel stream, you want to make sure that you are using a thread-safe collection,
since its add method will be called from multiple threads. This approach is demonstrated in Listing 7-8.
Listing 7-8. Bridging Streams to Collections Using Add
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
public class Listing8 {
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();
}
 
Search WWH ::




Custom Search