חלקPart 5: Java מודרנית וכליםModern Java & tools
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
Streams ו-OptionalStreams & Optional
filter, map, reduce ו-collect, groupingBy, ו-Optional במקום null.
filter, map, reduce and collect, groupingBy, and Optional instead of null.
הנקודות החשובותKey points
- Stream: "פס ייצור" על אוסף:Stream: A "production line" over a collection:
- פעולת ביניים: פעולה שמחזירה Stream חדש:intermediate operation: An operation returning a new Stream:
- ה-Stream עובר ספר-ספר:
filterמשאיר רק מה שאחרי 1900,mapהופך ספר לכותר,sortedממיין, ו-toListאוסף.The Stream goes book by book:filterkeeps what's after 1900,mapturns a book into its title,sortedsorts, andtoListcollects. - הרשימה המקורית לא משתנה.The original list doesn't change.
mapToIntנותןIntStreamעםsum,average,min.mapToIntgives anIntStreamwithsum,average,min.averageמחזירOptionalDouble(אולי אין ספרים), ולכןorElse(0).averagereturns anOptionalDouble(maybe there are no books), henceorElse(0).groupingBy(Book::author, TreeMap::new, counting())בונה מפה ממוינת מסופר לכמות.groupingBy(Book::author, TreeMap::new, counting())builds a sorted map from author to count.joiningמחבר מחרוזות עם מפריד, תחילית וסיומת.joiningglues strings with a separator, prefix and suffix.findFirstמחזיר Optional: אולי מצאנו, אולי לא.findFirstreturns an Optional: maybe found, maybe not.
מונחיםTerms
- StreamStream: "פס ייצור" על אוסף:
books.stream().filter(...).map(...).toList(). לא משנה את האוסף המקורי.A "production line" over a collection:books.stream().filter(...).map(...).toList(). It doesn't change the original collection. - פעולת בינייםintermediate operation: פעולה שמחזירה Stream חדש:
filter,map,sorted,distinct,flatMap. לבד היא לא מריצה כלום.An operation returning a new Stream:filter,map,sorted,distinct,flatMap. On its own it runs nothing. - פעולת סיוםterminal operation: הפעולה שמריצה את כל הפס ומחזירה תוצאה:
toList,count,sum,collect,findFirst,forEach. אחריה ה-Stream סגור.The operation that runs the whole line and returns a result:toList,count,sum,collect,findFirst,forEach. After it the Stream is closed. - CollectorsCollectors: מתכונים ל-
collect:groupingBy(מפה לפי מפתח),counting,mapping,joining,partitioningBy,toMap.Recipes forcollect:groupingBy(a map by key),counting,mapping,joining,partitioningBy,toMap. - OptionalOptional: קופסה שאולי יש בה ערך.
findFirstמחזירOptional, ומטפלים במקרה הריק במפורש:orElse,map,ifPresentOrElse. בלי NullPointerException.A box that may hold a value.findFirstreturns anOptional, and you handle the empty case explicitly:orElse,map,ifPresentOrElse. No NullPointerException. - עצלותlaziness: פעולות ביניים לא רצות עד שיש פעולת סיום, ו-Stream אפשר להריץ פעם אחת בלבד. פעם שנייה:
IllegalStateException: stream has already been operated upon or closed.Intermediate operations don't run until there's a terminal operation, and a Stream can run once only. A second time:IllegalStateException: stream has already been operated upon or closed. - StreamStream: "פס ייצור" על אוסף:
books.stream().filter(...).map(...).toList(). לא משנה את האוסף המקורי.A "production line" over a collection:books.stream().filter(...).map(...).toList(). It doesn't change the original collection. - פעולת בינייםintermediate operation: פעולה שמחזירה Stream חדש:
filter,map,sorted,distinct,flatMap. לבד היא לא מריצה כלום.An operation returning a new Stream:filter,map,sorted,distinct,flatMap. On its own it runs nothing. - פעולת סיוםterminal operation: הפעולה שמריצה את כל הפס ומחזירה תוצאה:
toList,count,sum,collect,findFirst,forEach. אחריה ה-Stream סגור.The operation that runs the whole line and returns a result:toList,count,sum,collect,findFirst,forEach. After it the Stream is closed. - CollectorsCollectors: מתכונים ל-
collect:groupingBy(מפה לפי מפתח),counting,mapping,joining,partitioningBy,toMap.Recipes forcollect:groupingBy(a map by key),counting,mapping,joining,partitioningBy,toMap. - OptionalOptional: קופסה שאולי יש בה ערך.
findFirstמחזירOptional, ומטפלים במקרה הריק במפורש:orElse,map,ifPresentOrElse. בלי NullPointerException.A box that may hold a value.findFirstreturns anOptional, and you handle the empty case explicitly:orElse,map,ifPresentOrElse. No NullPointerException. - עצלותlaziness: פעולות ביניים לא רצות עד שיש פעולת סיום, ו-Stream אפשר להריץ פעם אחת בלבד. פעם שנייה:
IllegalStateException: stream has already been operated upon or closed.Intermediate operations don't run until there's a terminal operation, and a Stream can run once only. A second time:IllegalStateException: stream has already been operated upon or closed.
Cheatsheet
filter, map, sorted, toListfilter, map, sorted, toList
List<Book> books = List.of(new Book("Emma", "Austen", 1815, 474, 4), new Book("Dune", "Herbert", 1965, 412, 5), new Book("Persuasion", "Austen", 1817, 249, 5), new Book("Ulysses", "Joyce", 1922, 730, 3));
List<String> modern = books.stream()
.filter(b -> b.year() > 1900)
.map(Book::title)
.sorted()
.toList();
System.out.println(modern);
System.out.println(books.stream().filter(b -> b.rating() == 5).count());מספרים: sum, average, min, reduceNumbers: sum, average, min, reduce
List<Book> books = List.of(new Book("Emma", "Austen", 1815, 474, 4), new Book("Dune", "Herbert", 1965, 412, 5), new Book("Persuasion", "Austen", 1817, 249, 5), new Book("Ulysses", "Joyce", 1922, 730, 3));
int pages = books.stream().mapToInt(Book::pages).sum();
double avg = books.stream().mapToInt(Book::rating).average().orElse(0);
int oldest = books.stream().mapToInt(Book::year).min().getAsInt();
System.out.println(pages + " " + avg + " " + oldest);
System.out.println(books.stream().map(Book::title).reduce("", (a, b) -> a + b.charAt(0)));groupingBy ו-joininggroupingBy and joining
List<Book> books = List.of(new Book("Emma", "Austen", 1815, 474, 4), new Book("Dune", "Herbert", 1965, 412, 5), new Book("Persuasion", "Austen", 1817, 249, 5), new Book("Ulysses", "Joyce", 1922, 730, 3));
Map<String, Long> perAuthor = books.stream()
.collect(Collectors.groupingBy(Book::author, TreeMap::new, Collectors.counting()));
System.out.println(perAuthor);
String titles = books.stream().map(Book::title).collect(Collectors.joining(", ", "[", "]"));
System.out.println(titles);Optional במקום nullOptional instead of null
List<Book> books = List.of(new Book("Emma", "Austen", 1815, 474, 4), new Book("Dune", "Herbert", 1965, 412, 5), new Book("Persuasion", "Austen", 1817, 249, 5), new Book("Ulysses", "Joyce", 1922, 730, 3));
Optional<Book> found = books.stream().filter(b -> b.title().equals("Dune")).findFirst();
Optional<Book> missing = books.stream().filter(b -> b.title().equals("Hamlet")).findFirst();
System.out.println(found.map(Book::author).orElse("?") + " " + missing.map(Book::author).orElse("?"));
missing.ifPresentOrElse(b -> System.out.println("found"), () -> System.out.println("not on the shelf"));שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
IllegalStateException | Stream רץ פעם אחתA Stream runs once | IllegalStateException: stream has already been operated upon or closed: יוצרים Stream חדש לכל שאלה.IllegalStateException: stream has already been operated upon or closed: make a new Stream for each question. |
IllegalStateException | צייד באגים: Stream פעמייםBug hunter: a Stream twice | IllegalStateException: stream has already been operated upon or closed: count() סגר את ה-Stream.IllegalStateException: stream has already been operated upon or closed: count() closed the Stream. |