Java Reference
In-Depth Information
remove map elements, prefer the use of a foreach loop and use one of the methods
of iteration shown in the solution to this recipe.
7-10. Executing Streams in Parallel
Problem
You want to iterate over a Collection in parallel to distribute the work over mul-
tiple CPUs.
Solution
Utilize a stream construct on the Collection , and invoke parallelStream() as
the first intermediate operation in order to take advantage of multiple CPU processing.
The following class demonstrates multiple uses of the parallelStream() opera-
tion:
public class StockPortfolio2 {
static List<Stock> myStocks = new ArrayList();
private static void createStocks(){
myStocks.add(new Stock("ORCL", "Oracle", 500.0));
myStocks.add(new Stock("AAPL", "Apple", 200.0));
myStocks.add(new Stock("GOOG", "Google", 100.0));
myStocks.add(new Stock("IBM", "IBM", 50.0));
myStocks.add(new Stock("MCD", "McDonalds",
300.0));
}
public static void main(String[] args){
createStocks();
// Iterate over each element and print the stock
names
myStocks.stream()
.forEach(s->System.out.println(s.getName()));
Search WWH ::




Custom Search