Java 17 Recipes


-10. Executing Streams in Parallel


Download 3.2 Mb.
Pdf ko'rish
bet148/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   144   145   146   147   148   149   150   151   ...   245
Bog'liq
Java 17 Recipes

7-10. Executing Streams in Parallel
 Problem
You want to iterate a collection parallel to distribute the work over multiple 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() operation.
Chapter 7 Data SourCeS anD ColleCtionS


289
public class StockPortfolio2 {
static List 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()));
boolean allGt = myStocks.parallelStream()
.allMatch(s->s.getShares() > 100.0);
System.out.println("All Stocks Greater Than 100.0 Shares? " 
+ allGt);
// Print out all stocks that have more than 100 shares
System.out.println("== We have more than 100 shares of the 
following:");
myStocks.parallelStream()
.filter(s -> s.getShares() > 100.0)
.forEach(s->System.out.println(s.getName()));
System.out.println("== The following stocks are sorted by 
shares:");
Comparator byShares =
Comparator.comparing(Stock::getShares);
Stream sortedByShares = myStocks.parallelStream()
.sorted(byShares);
sortedByShares.forEach(s -> System.out.println("Stock: " + 
s.getName() + " - Shares: " + s.getShares()));
Chapter 7 Data SourCeS anD ColleCtionS


290
// May or may not return a value
Optional maybe = myStocks.parallelStream()
.findFirst();
System.out.println("First Stock: " + maybe.get().getName());
List newStocks = new ArrayList();
Optional maybeNot = newStocks.parallelStream()
.findFirst();
Consumer myConsumer = (s) ->
{
System.out.println("First Stock (Optional): " + s.getName());
};
maybeNot.ifPresent(myConsumer);
if(maybeNot.isPresent()){
System.out.println(maybeNot.get().getName());
}
newStocks.add(new Stock("MCD", "McDonalds", 300.0));
Optional maybeNow = newStocks.stream()
.findFirst();
maybeNow.ifPresent(myConsumer);
}
}

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   144   145   146   147   148   149   150   151   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling