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

JavaJava
26
חלקPart 5: Java מודרנית וכליםModern Java & tools כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Lambdas ו-functional interfacesLambdas & functional interfaces

ביטויי למבדה, Function, Predicate, Consumer ו-Supplier, ו-method references.

Lambda expressions, Function, Predicate, Consumer and Supplier, and method references.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

מיון עם למבדהSorting with a lambda

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

מיינו Noa, Avraham, Dan, Michal לפי אורך עם למבדה ([Noa, Dan, Michal, Avraham]), ואז לפי אורך יורד, ובשוויון לפי א-ב, עם Comparator.comparing: [Avraham, Michal, Dan, Noa].

Sort Noa, Avraham, Dan, Michal by length with a lambda ([Noa, Dan, Michal, Avraham]), then by length descending, ties alphabetical, with Comparator.comparing: [Avraham, Michal, Dan, Noa].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Noa", "Avraham", "Dan", "Michal"));
        names.sort((a, b) -> Integer.compare(a.length(), b.length()));
        System.out.println(names);
        names.sort(Comparator.comparing(String::length).reversed().thenComparing(Comparator.naturalOrder()));
        System.out.println(names);
    }
}
פלטOutput
[Noa, Dan, Michal, Avraham]
[Avraham, Michal, Dan, Noa]

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

תרגילExercise 2

מסננים עם PredicateFilters with a Predicate

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

static List<Book> filter(List<Book> books, Predicate<Book> rule). עם old (לפני 1950) ו-great (דירוג 4 ומעלה): הדפיסו [Emma, Ulysses], [Emma] (and), ו-[Dune, Ulysses] (חדש או מתחיל ב-U).

static List<Book> filter(List<Book> books, Predicate<Book> rule). With old (before 1950) and great (rating 4 or more): print [Emma, Ulysses], [Emma] (and), and [Dune, Ulysses] (new or starting with U).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Main {
    static List<Book> filter(List<Book> books, Predicate<Book> rule) {
        List<Book> out = new ArrayList<>();
        for (Book b : books) {
            if (rule.test(b)) {
                out.add(b);
            }
        }
        return out;
    }

    public static void main(String[] args) {
        List<Book> books = List.of(new Book("Emma", 1815, 4), new Book("Dune", 1965, 5), new Book("Ulysses", 1922, 3));
        Predicate<Book> old = b -> b.year() < 1950;
        Predicate<Book> great = b -> b.rating() >= 4;
        System.out.println(filter(books, old));
        System.out.println(filter(books, old.and(great)));
        System.out.println(filter(books, old.negate().or(b -> b.title().startsWith("U"))));
    }
}

record Book(String title, int year, int rating) {
    @Override
    public String toString() {
        return title;
    }
}
פלטOutput
[Emma, Ulysses]
[Emma]
[Dune, Ulysses]

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

תרגילExercise 3

שרשרת פונקציותA chain of functions

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

trim.andThen(upper) מנקה מחרוזת. הדפיסו [DUNE] עבור " dune ", את האורך אחרי הניקוי (4), ו-12 (twice פעמיים על 3).

trim.andThen(upper) cleans a string. Print [DUNE] for " dune ", the length after cleaning (4), and 12 (twice twice on 3).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.function.Function;
import java.util.function.UnaryOperator;

public class Main {
    public static void main(String[] args) {
        Function<String, String> trim = String::trim;
        Function<String, String> upper = String::toUpperCase;
        Function<String, Integer> length = String::length;
        Function<String, String> clean = trim.andThen(upper);
        System.out.println("[" + clean.apply("  dune ") + "]");
        System.out.println(clean.andThen(length).apply("  dune "));
        UnaryOperator<Integer> twice = x -> x * 2;
        System.out.println(twice.andThen(twice).apply(3));
    }
}
פלטOutput
[DUNE]
4
12

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

תרגילExercise 4

צייד באגים: משתנה בתוך למבדהBug hunter: a variable inside a lambda

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

התוכנית מהתזכורת לא מתקמפלת. כתבו את הספירה בלולאה רגילה כך שיודפס 6.

The program from the refresher doesn't compile. Write the count as a plain loop so it prints 6.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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<String> words = List.of("a", "bb", "ccc");
        int total = 0;
        for (String w : words) {
            total += w.length();
        }
        System.out.println(total);
    }
}
פלטOutput
6

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

תרגילExercise 5

מחשבון של למבדותA calculator of lambdas

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

@FunctionalInterface interface Op { int apply(int a, int b); }. מפה ממוינת מסימן לפעולה: +, -, max (Math::max) ו-pow (למבדה עם בלוק). הדפיסו לכל אחת על 2 ו-5: + -> 7, - -> -3, max -> 5, pow -> 32.

@FunctionalInterface interface Op { int apply(int a, int b); }. A sorted map from a symbol to an operation: +, -, max (Math::max) and pow (a lambda with a block). Print each on 2 and 5: + -> 7, - -> -3, max -> 5, pow -> 32.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Op> ops = new TreeMap<>();
        ops.put("+", (a, b) -> a + b);
        ops.put("-", (a, b) -> a - b);
        ops.put("max", Math::max);
        ops.put("pow", (a, b) -> {
            int r = 1;
            for (int i = 0; i < b; i++) {
                r *= a;
            }
            return r;
        });
        for (String name : ops.keySet()) {
            System.out.println(name + " -> " + ops.get(name).apply(2, 5));
        }
    }
}

@FunctionalInterface
interface Op {
    int apply(int a, int b);
}
פלטOutput
+ -> 7
- -> -3
max -> 5
pow -> 32

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

תרגילExercise 6

מדף, צעד 26: סינון ספרים עם PredicateShelf, step 26: filtering books with a Predicate

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

ל-Shelf הוסיפו find(Predicate<Book>), count(Predicate<Book>) ו-static Predicate<Book> byAuthor(String). הדפיסו [Emma, Persuasion], [Persuasion], [Emma, Ulysses], 2.

Add find(Predicate<Book>), count(Predicate<Book>) and static Predicate<Book> byAuthor(String) to Shelf. Print [Emma, Persuasion], [Persuasion], [Emma, Ulysses], 2.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Shelf s = new Shelf();
        s.add(new Book("Emma", "Austen", 1815, 4));
        s.add(new Book("Dune", "Herbert", 1965, 5));
        s.add(new Book("Persuasion", "Austen", 1817, 5));
        s.add(new Book("Ulysses", "Joyce", 1922, 3));
        Predicate<Book> byAusten = Shelf.byAuthor("Austen");
        Predicate<Book> topRated = b -> b.rating() == 5;
        System.out.println(s.find(byAusten));
        System.out.println(s.find(byAusten.and(topRated)));
        System.out.println(s.find(topRated.negate()));
        System.out.println(s.count(b -> b.year() > 1900));
    }
}

record Book(String title, String author, int year, int rating) {
    @Override
    public String toString() {
        return title;
    }
}

class Shelf {
    private final List<Book> books = new ArrayList<>();

    void add(Book b) {
        books.add(b);
    }

    List<Book> find(Predicate<Book> rule) {
        List<Book> out = new ArrayList<>();
        for (Book b : books) {
            if (rule.test(b)) {
                out.add(b);
            }
        }
        return out;
    }

    int count(Predicate<Book> rule) {
        return find(rule).size();
    }

    static Predicate<Book> byAuthor(String author) {
        return b -> b.author().equals(author);
    }
}
פלטOutput
[Emma, Persuasion]
[Persuasion]
[Emma, Ulysses]
2

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

אתגרChallenge 1

פונקציה שמחזירה פונקציהA function returning a function

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

Function<Integer, Function<Integer, Integer>> add = a -> b -> a + b;. add.apply(10) היא "הוסף 10". הדפיסו 15 3, ואז 22 (times.andThen(plus10) על 3 ו-4).

Function<Integer, Function<Integer, Integer>> add = a -> b -> a + b;. add.apply(10) is "add 10". Print 15 3, then 22 (times.andThen(plus10) on 3 and 4).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.function.BiFunction;
import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Function<Integer, Integer>> add = a -> b -> a + b;
        Function<Integer, Integer> plus10 = add.apply(10);
        System.out.println(plus10.apply(5) + " " + add.apply(1).apply(2));
        BiFunction<Integer, Integer, Integer> times = (a, b) -> a * b;
        System.out.println(times.andThen(plus10).apply(3, 4));
    }
}
פלטOutput
15 3
22

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

אתגרChallenge 2

ארבעה סוגי method referenceFour kinds of method reference

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

כתבו method reference מכל סוג: static (Integer::parseInt), של עצם מסוים (prefix::concat), של כל עצם מהטיפוס (String::length), ובנאי (Book::new). הדפיסו 43, Book: Dune 4, Book[title=Emma, year=1815] [].

Write a method reference of each kind: static (Integer::parseInt), of a particular object (prefix::concat), of any object of the type (String::length), and a constructor (Book::new). Print 43, Book: Dune 4, Book[title=Emma, year=1815] [].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;

public class Main {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;
        String prefix = "Book: ";
        Function<String, String> label = prefix::concat;
        Function<String, Integer> size = String::length;
        BiFunction<String, Integer, Book> make = Book::new;
        Supplier<List<String>> empty = List::of;
        System.out.println(parse.apply("42") + 1);
        System.out.println(label.apply("Dune") + " " + size.apply("Dune"));
        System.out.println(make.apply("Emma", 1815) + " " + empty.get());
    }
}

record Book(String title, int year) {
}
פלטOutput
43
Book: Dune 4
Book[title=Emma, year=1815] []

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

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