Streams ו-OptionalStreams & Optional
filter, map, reduce ו-collect, groupingBy, ו-Optional במקום null.
filter, map, reduce and collect, groupingBy, and Optional instead of null.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- Stream: "פס ייצור" על אוסף:
books.stream().filter(...).map(...).toList(). לא משנה את האוסף המקורי.Stream: A "production line" over a collection:books.stream().filter(...).map(...).toList(). It doesn't change the original collection. - פעולת ביניים: פעולה שמחזירה Stream חדש:
filter,map,sorted,distinct,flatMap. לבד היא לא מריצה כלום.intermediate operation: An operation returning a new Stream:filter,map,sorted,distinct,flatMap. On its own it runs nothing. - פעולת סיום: הפעולה שמריצה את כל הפס ומחזירה תוצאה:
toList,count,sum,collect,findFirst,forEach. אחריה ה-Stream סגור.terminal operation: The operation that runs the whole line and returns a result:toList,count,sum,collect,findFirst,forEach. After it the Stream is closed. - Collectors: מתכונים ל-
collect:groupingBy(מפה לפי מפתח),counting,mapping,joining,partitioningBy,toMap.Collectors: Recipes forcollect:groupingBy(a map by key),counting,mapping,joining,partitioningBy,toMap. - Optional: קופסה שאולי יש בה ערך.
findFirstמחזירOptional, ומטפלים במקרה הריק במפורש:orElse,map,ifPresentOrElse. בלי NullPointerException.Optional: A box that may hold a value.findFirstreturns anOptional, and you handle the empty case explicitly:orElse,map,ifPresentOrElse. No NullPointerException. - עצלות: פעולות ביניים לא רצות עד שיש פעולת סיום, ו-Stream אפשר להריץ פעם אחת בלבד. פעם שנייה:
IllegalStateException: stream has already been operated upon or closed.laziness: 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.
02filter, map, sorted, toListfilter, map, sorted, toList
ה-Stream עובר ספר-ספר: filter משאיר רק מה שאחרי 1900, map הופך ספר לכותר, sorted ממיין, ו-toList אוסף. הרשימה המקורית לא משתנה. צפו בסימולציה: הלמבדה של filter נקראת על כל ספר.
The Stream goes book by book: filter keeps what's after 1900, map turns a book into its title, sorted sorts, and toList collects. The original list doesn't change. Watch the simulation: filter's lambda is called on each book.
import java.util.List;
public class Main {
public static void main(String[] args) {
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());
}
}
record Book(String title, String author, int year, int pages, int rating) {
}[Dune, Ulysses] 2
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03מספרים: sum, average, min, reduceNumbers: sum, average, min, reduce
mapToInt נותן IntStream עם sum, average, min. average מחזיר OptionalDouble (אולי אין ספרים), ולכן orElse(0). reduce מצמצם הכול לערך אחד.
mapToInt gives an IntStream with sum, average, min. average returns an OptionalDouble (maybe there are no books), hence orElse(0). reduce folds everything into one value.
import java.util.List;
public class Main {
public static void main(String[] args) {
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)));
}
}
record Book(String title, String author, int year, int pages, int rating) {
}1865 4.25 1815 EDPU
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04groupingBy ו-joininggroupingBy and joining
groupingBy(Book::author, TreeMap::new, counting()) בונה מפה ממוינת מסופר לכמות. joining מחבר מחרוזות עם מפריד, תחילית וסיומת.
groupingBy(Book::author, TreeMap::new, counting()) builds a sorted map from author to count. joining glues strings with a separator, prefix and suffix.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
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);
}
}
record Book(String title, String author, int year, int pages, int rating) {
}{Austen=2, Herbert=1, Joyce=1}
[Emma, Dune, Persuasion, Ulysses]צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05Optional במקום nullOptional instead of null
findFirst מחזיר Optional: אולי מצאנו, אולי לא. map(...).orElse("?") מטפל בשני המקרים בלי if (x != null).
findFirst returns an Optional: maybe found, maybe not. map(...).orElse("?") handles both cases with no if (x != null).
import java.util.List;
import java.util.Optional;
public class Main {
public static void main(String[] args) {
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"));
}
}
record Book(String title, String author, int year, int pages, int rating) {
}Herbert ? not on the shelf
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06Stream רץ פעם אחתA Stream runs once
count() הוא פעולת סיום וסוגר את ה-Stream. השימוש השני בו זורק חריגה.
count() is a terminal operation and closes the Stream. Using it a second time throws.
Stream רץ פעם אחת
A Stream runs once
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
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));
Stream<Book> s = books.stream().filter(b -> b.rating() >= 4);
System.out.println(s.count());
System.out.println(s.map(Book::title).toList());
}
}
record Book(String title, String author, int year, int pages, int rating) {
}3 Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.base/java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203) at java.base/java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:96) at java.base/java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:800) at java.base/java.util.stream.ReferencePipeline$3.<init>(ReferencePipeline.java:191) at java.base/java.util.stream.ReferencePipeline.map(ReferencePipeline.java:190) at Main.main(Main.java:9)
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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
07טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.
These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.
צייד באגים: Stream פעמיים
Bug hunter: a Stream twice
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
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));
Stream<Book> s = books.stream().filter(b -> b.rating() >= 4);
System.out.println(s.count());
System.out.println(s.map(Book::title).toList());
}
}
record Book(String title, String author, int year, int pages, int rating) {
}3 Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed at java.base/java.util.stream.AbstractPipeline.<init>(AbstractPipeline.java:203) at java.base/java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:96) at java.base/java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:800) at java.base/java.util.stream.ReferencePipeline$3.<init>(ReferencePipeline.java:191) at java.base/java.util.stream.ReferencePipeline.map(ReferencePipeline.java:190) at Main.main(Main.java:9)
IllegalStateException: stream has already been operated upon or closed: count() סגר את ה-Stream.IllegalStateException: stream has already been operated upon or closed: count() closed the Stream.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
08הצעד של היום בפרויקט מדףToday's step in the Shelf project
עם summaryStatistics() הדפיסו 4 books, rating 3-5, avg 4.25. מצאו את הטוב ביותר (דירוג, ובשוויון השנה המאוחרת): Best: Dune. ואז את הסופרים בלי כפולים, ממוינים: Austen | Herbert | Joyce.
With summaryStatistics() print 4 books, rating 3-5, avg 4.25. Find the best (rating, ties by the later year): Best: Dune. Then the authors without duplicates, sorted: Austen | Herbert | Joyce.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.