נבנה על ידי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.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

כותרים חדשים באותיות גדולותNew titles in capitals

תזכורת: מה ביקשוReminder: the task

מהמדף (Emma 1815, Dune 1965, Persuasion 1817, Ulysses 1922) קחו את הספרים אחרי 1816, הפכו את הכותר לאותיות גדולות, מיינו ואספו: [DUNE, PERSUASION, ULYSSES].

From the shelf (Emma 1815, Dune 1965, Persuasion 1817, Ulysses 1922) take the books after 1816, upper-case the title, sort and collect: [DUNE, PERSUASION, ULYSSES].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
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> names = books.stream()
                .filter(b -> b.year() > 1816)
                .map(b -> b.title().toUpperCase())
                .sorted()
                .toList();
        System.out.println(names);
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
[DUNE, PERSUASION, ULYSSES]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

סכום וממוצעSum and average

תזכורת: מה ביקשוReminder: the task

הדפיסו את סך העמודים, את ממוצע העמודים של Austen, ואת הממוצע של סופר שאין לו ספרים (0.0): 1865 361.5 0.0.

Print the total pages, Austen's average pages, and the average of an author with no books (0.0): 1865 361.5 0.0.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
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 total = books.stream().mapToInt(Book::pages).sum();
        double avgAusten = books.stream().filter(b -> b.author().equals("Austen")).mapToInt(Book::pages).average().orElse(0);
        double avgNobody = books.stream().filter(b -> b.author().equals("Nobody")).mapToInt(Book::pages).average().orElse(0);
        System.out.println(total + " " + avgAusten + " " + avgNobody);
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
1865 361.5 0.0

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

קיבוץGrouping

תזכורת: מה ביקשוReminder: the task

בנו TreeMap מסופר לכמות ספרים ({Austen=2, Herbert=1, Joyce=1}), ו-TreeMap מדירוג לרשימת כותרים ({3=[Ulysses], 4=[Emma], 5=[Dune, Persuasion]}).

Build a TreeMap from author to book count ({Austen=2, Herbert=1, Joyce=1}), and a TreeMap from rating to a list of titles ({3=[Ulysses], 4=[Emma], 5=[Dune, Persuasion]}).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
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> counts = books.stream()
                .collect(Collectors.groupingBy(Book::author, TreeMap::new, Collectors.counting()));
        Map<Integer, List<String>> byRating = books.stream()
                .collect(Collectors.groupingBy(Book::rating, TreeMap::new, Collectors.mapping(Book::title, Collectors.toList())));
        System.out.println(counts);
        System.out.println(byRating);
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
{Austen=2, Herbert=1, Joyce=1}
{3=[Ulysses], 4=[Emma], 5=[Dune, Persuasion]}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

מי כתב את זה?Who wrote it?

תזכורת: מה ביקשוReminder: the task

static String authorOf(List<Book> books, String title) עם findFirst, map ו-orElse("unknown"), בלי null ובלי if. הדפיסו Herbert ואז unknown.

static String authorOf(List<Book> books, String title) with findFirst, map and orElse("unknown"), no null and no if. Print Herbert then unknown.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.List;
import java.util.Optional;

public class Main {
    static String authorOf(List<Book> books, String title) {
        Optional<Book> b = books.stream().filter(x -> x.title().equals(title)).findFirst();
        return b.map(Book::author).orElse("unknown");
    }

    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));
        System.out.println(authorOf(books, "Dune"));
        System.out.println(authorOf(books, "Hamlet"));
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
Herbert
unknown

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

צייד באגים: Stream פעמייםBug hunter: a Stream twice

תזכורת: מה ביקשוReminder: the task

התוכנית מהתזכורת קורסת. תקנו כך שכל שאלה תקבל Stream משלה, ויודפס 3 ואז [Emma, Dune, Persuasion].

The program from the refresher crashes. Fix it so each question gets its own Stream, printing 3 then [Emma, Dune, Persuasion].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו איפה זה נשברWatch where it breaks
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
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));
        System.out.println(books.stream().filter(b -> b.rating() >= 4).count());
        System.out.println(books.stream().filter(b -> b.rating() >= 4).map(Book::title).toList());
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
3
[Emma, Dune, Persuasion]

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 6

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

תזכורת: מה ביקשוReminder: the task

עם 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.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
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));
        IntSummaryStatistics st = books.stream().mapToInt(Book::rating).summaryStatistics();
        System.out.println(String.format("%d books, rating %d-%d, avg %.2f", st.getCount(), st.getMin(), st.getMax(), st.getAverage()));
        String best = books.stream().max(Comparator.comparingInt(Book::rating).thenComparing(Book::year)).map(Book::title).orElse("-");
        System.out.println("Best: " + best);
        System.out.println(books.stream().map(Book::author).distinct().sorted().collect(Collectors.joining(" | ")));
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
4 books, rating 3-5, avg 4.25
Best: Dune
Austen | Herbert | Joyce

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

flatMap לתגיותflatMap for tags

תזכורת: מה ביקשוReminder: the task

לכל פוסט יש רשימת תגיות. עם flatMap הפכו את כל התגיות לזרם אחד, בלי כפולים וממוין: [git, java, oop, streams]. אחר כך את מספר התגיות הכולל (5).

Each post has a list of tags. With flatMap turn all tags into one stream, without duplicates and sorted: [git, java, oop, streams]. Then the total number of tags (5).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Post> posts = List.of(new Post("a", List.of("java", "oop")), new Post("b", List.of("java", "streams")), new Post("c", List.of("git")));
        List<String> tags = posts.stream().flatMap(p -> p.tags().stream()).distinct().sorted().toList();
        System.out.println(tags);
        System.out.println(posts.stream().mapToInt(p -> p.tags().size()).sum());
    }
}

record Post(String id, List<String> tags) {
}
פלטOutput
[git, java, oop, streams]
5

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

partitioningBy ו-toMappartitioningBy and toMap

תזכורת: מה ביקשוReminder: the task

חלקו לספרים ארוכים (מעל 450 עמודים) וקצרים: long: [Emma, Ulysses] short: [Dune, Persuasion]. אחר כך מפה ממוינת מסופר לסך העמודים (toMap עם Integer::sum): {Austen=723, Herbert=412, Joyce=730}.

Split into long books (over 450 pages) and short: long: [Emma, Ulysses] short: [Dune, Persuasion]. Then a sorted map from author to total pages (toMap with Integer::sum): {Austen=723, Herbert=412, Joyce=730}.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line

לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.

Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.

צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

הפתרון המלא והפלט שלוFull solution and its output
Main.java
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<Boolean, List<String>> split = books.stream()
                .collect(Collectors.partitioningBy(b -> b.pages() > 450, Collectors.mapping(Book::title, Collectors.toList())));
        System.out.println("long: " + split.get(true) + " short: " + split.get(false));
        Map<String, Integer> pagesByAuthor = books.stream()
                .collect(Collectors.toMap(Book::author, Book::pages, Integer::sum, TreeMap::new));
        System.out.println(pagesByAuthor);
    }
}

record Book(String title, String author, int year, int pages, int rating) {
}
פלטOutput
long: [Emma, Ulysses] short: [Dune, Persuasion]
{Austen=723, Herbert=412, Joyce=730}

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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