נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
27
חלק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.

או Ctrl+Por Ctrl+P

הנקודות החשובות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: filter keeps what's after 1900, map turns a book into its title, sorted sorts, and toList collects.
  • הרשימה המקורית לא משתנה.The original list doesn't change.
  • mapToInt נותן IntStream עם sum, average, min.mapToInt gives an IntStream with sum, average, min.
  • average מחזיר OptionalDouble (אולי אין ספרים), ולכן orElse(0).average returns an OptionalDouble (maybe there are no books), hence orElse(0).
  • groupingBy(Book::author, TreeMap::new, counting()) בונה מפה ממוינת מסופר לכמות.groupingBy(Book::author, TreeMap::new, counting()) builds a sorted map from author to count.
  • joining מחבר מחרוזות עם מפריד, תחילית וסיומת.joining glues strings with a separator, prefix and suffix.
  • findFirst מחזיר Optional: אולי מצאנו, אולי לא.findFirst returns 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 for collect: groupingBy (a map by key), counting, mapping, joining, partitioningBy, toMap.
  • OptionalOptional: קופסה שאולי יש בה ערך. findFirst מחזיר Optional, ומטפלים במקרה הריק במפורש: orElse, map, ifPresentOrElse. בלי NullPointerException.A box that may hold a value. findFirst returns an Optional, 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 for collect: groupingBy (a map by key), counting, mapping, joining, partitioningBy, toMap.
  • OptionalOptional: קופסה שאולי יש בה ערך. findFirst מחזיר Optional, ומטפלים במקרה הריק במפורש: orElse, map, ifPresentOrElse. בלי NullPointerException.A box that may hold a value. findFirst returns an Optional, 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
IllegalStateExceptionStream רץ פעם אחתA Stream runs onceIllegalStateException: 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 twiceIllegalStateException: stream has already been operated upon or closed: count() סגר את ה-Stream.IllegalStateException: stream has already been operated upon or closed: count() closed the Stream.

נבנה על ידיBuilt by Ariel Yohimovich