Java 17 Recipes
-10. Executing Streams in Parallel
Download 3.2 Mb. Pdf ko'rish
|
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 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 Comparator.comparing(Stock::getShares); Stream .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 .findFirst(); System.out.println("First Stock: " + maybe.get().getName()); List newStocks = new ArrayList(); Optional .findFirst(); Consumer { 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 .findFirst(); maybeNow.ifPresent(myConsumer); } } Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling