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

חזרה למפגשBack
JavaJava

Streams ו-OptionalStreams & Optional

מפגש 27: filter, map, reduce ו-collect, groupingBy, ו-Optional במקום null.Session 27: filter, map, reduce and collect, groupingBy, and Optional instead of null.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • filter, map, sorted, toListfilter, map, sorted, toList
  • מספרים: sum, average, min, reduceNumbers: sum, average, min, reduce
  • groupingBy ו-joininggroupingBy and joining
  • Optional במקום nullOptional instead of null
  • Stream רץ פעם אחתA Stream runs once
נושאTopic 1

מונחיםTerms

המונחים של המפגשThis session's terms

  • Stream: "פס ייצור" על אוסף:Stream: A "production line" over a collection:
  • פעולת ביניים: פעולה שמחזירה Stream חדש:intermediate operation: An operation returning a new Stream:
  • פעולת סיום: הפעולה שמריצה את כל הפס ומחזירה תוצאה:terminal operation: The operation that runs the whole line and returns a result:
  • Collectors: מתכונים ל-collect:Collectors: Recipes for collect:
  • Optional: קופסה שאולי יש בה ערך.Optional: A box that may hold a value.
  • עצלות: פעולות ביניים לא רצות עד שיש פעולת סיום, ו-Stream אפשר להריץ פעם אחת בלבד.laziness: Intermediate operations don't run until there's a terminal operation, and a Stream can run once only.
נושאTopic 2

filter, map, sorted, toListfilter, map, sorted, toList

filter, map, sorted, toListfilter, map, sorted, toList

  • ה-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.
  • צפו בסימולציה: הלמבדה של filter נקראת על כל ספר.Watch the simulation: filter's lambda is called on each book.
נושאTopic 3

מספרים: sum, average, min, reduceNumbers: sum, average, min, reduce

מספרים: sum, average, min, reduceNumbers: sum, average, min, reduce

  • 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).
  • reduce מצמצם הכול לערך אחד.reduce folds everything into one value.
נושאTopic 4

groupingBy ו-joininggroupingBy and joining

groupingBy ו-joininggroupingBy and joining

  • 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.
נושאTopic 5

Optional במקום nullOptional instead of null

Optional במקום nullOptional instead of null

  • findFirst מחזיר Optional: אולי מצאנו, אולי לא.findFirst returns an Optional: maybe found, maybe not.
  • map(...).orElse("?") מטפל בשני המקרים בלי if (x != null).map(...).orElse("?") handles both cases with no if (x != null).
נושאTopic 6

Stream רץ פעם אחתA Stream runs once

Stream רץ פעם אחתA Stream runs once

  • count() הוא פעולת סיום וסוגר את ה-Stream.count() is a terminal operation and closes the Stream.
  • השימוש השני בו זורק חריגה.Using it a second time throws.
נושאTopic 7

טעויות נפוצותCommon mistakes

טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

  • `IllegalStateException:`IllegalStateException:
נושאTopic 8

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 27: סטטיסטיקות בשורהShelf, step 27: statistics in a line

Stream: "פס ייצור" על אוסף:Stream: A "production line" over a collection:

פעולת ביניים: פעולה שמחזירה Stream חדש:intermediate operation: An operation returning a new Stream:

פעולת סיום: הפעולה שמריצה את כל הפס ומחזירה תוצאה:terminal operation: The operation that runs the whole line and returns a result:

Collectors: מתכונים ל-collect:Collectors: Recipes for collect:

Optional: קופסה שאולי יש בה ערך.Optional: A box that may hold a value.

עצלות: פעולות ביניים לא רצות עד שיש פעולת סיום, ו-Stream אפשר להריץ פעם אחת בלבד.laziness: Intermediate operations don't run until there's a terminal operation, and a Stream can run once only.

ה-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.

צפו בסימולציה: הלמבדה של filter נקראת על כל ספר.Watch the simulation: filter's lambda is called on each book.

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).

reduce מצמצם הכול לערך אחד.reduce folds everything into one value.

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.

map(...).orElse("?") מטפל בשני המקרים בלי if (x != null).map(...).orElse("?") handles both cases with no if (x != null).

count() הוא פעולת סיום וסוגר את ה-Stream.count() is a terminal operation and closes the Stream.

השימוש השני בו זורק חריגה.Using it a second time throws.

`IllegalStateException:`IllegalStateException:

מדף, צעד 27: סטטיסטיקות בשורהShelf, step 27: statistics in a line

מה מחזיר books.stream().filter(b -> b.year() > 1900) לבד?What does books.stream().filter(b -> b.year() > 1900) return on its own?

  • רשימה מסוננתA filtered list
  • Stream, ושום דבר עוד לא רץA Stream, and nothing has run yet
  • מספרA number
  • שגיאהAn error

Stream, ושום דבר עוד לא רץA Stream, and nothing has run yet

list.stream().map(String::length).toList() משנה את list?Does list.stream().map(String::length).toList() change list?

  • כןYes
  • לא, היא מחזירה רשימה חדשהNo, it returns a new list
  • רק אם היא ArrayListOnly if it's an ArrayList
  • תלוי ב-mapIt depends on map

לא, היא מחזירה רשימה חדשהNo, it returns a new list

findFirst() על Stream ריק מחזיר?findFirst() on an empty Stream returns?

  • nullnull
  • Optional.empty()Optional.empty()
  • חריגהAn exception
  • 00

Optional.empty()Optional.empty()

מה למדנוWhat we learned

  • Stream: "פס ייצור" על אוסף:Stream: A "production line" over a collection:
  • ה-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.
  • mapToInt נותן IntStream עם sum, average, min.mapToInt gives an IntStream with sum, average, min.
  • groupingBy(Book::author, TreeMap::new, counting()) בונה מפה ממוינת מסופר לכמות.groupingBy(Book::author, TreeMap::new, counting()) builds a sorted map from author to count.
  • findFirst מחזיר Optional: אולי מצאנו, אולי לא.findFirst returns an Optional: maybe found, maybe not.
  • count() הוא פעולת סיום וסוגר את ה-Stream.count() is a terminal operation and closes the Stream.

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

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