Java 17 Recipes
-8. Iterating Collections
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
7-8. Iterating Collections
Problem Your application contains Collection within them. Solution Generate a stream on any type that extends or implements java.util.Collection and then perform the desired task(s) on each element of the collection. In the following code, an ArrayList public class StreamExample { 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)); } Chapter 7 Data SourCeS anD ColleCtionS 278 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.stream() .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.stream() .filter(s -> s.getShares() > 100.0) .forEach(s->System.out.println(s.getName())); System.out.println("== The following stocks are sorted by shares:"); Comparator comparing(Stock::getShares); Stream .sorted(byShares); sortedByShares.forEach(s -> System.out.println("Stock: " + s.getName() + " - Shares: " + s.getShares())); // 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()); }; Chapter 7 Data SourCeS anD ColleCtionS 279 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); } } The output is: Oracle Apple IBM McDonalds All Stocks Greater Than 100.0 Shares? false == We have more than 100 shares of the following: Oracle Apple McDonalds == The following stocks are sorted by shares: Stock: IBM - Shares: 50.0 Stock: Google - Shares: 100.0 Stock: Apple - Shares: 200.0 Stock: McDonalds - Shares: 300.0 Stock: Oracle - Shares: 500.0 First Stock: Oracle First Stock (Optional): McDonalds The results of executing this code demonstrate the concept of using streams. External iteration (for loops) is no longer a requirement for iterating over a data collection. Chapter 7 Data SourCeS anD ColleCtionS |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling