חלק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.
הנקודות החשובותKey points
- למבדה: פונקציה קצרה בלי שם:lambda: A short nameless function:
- functional interface: interface עם מתודה מופשטת אחת בדיוק (כמו
Comparator,Runnable,Predicate).functional interface: An interface with exactly one abstract method (likeComparator,Runnable,Predicate). - במפגש 24 כתבנו מחלקה שלמה בשביל Comparator.In session 24 we wrote a whole class for a Comparator.
- למבדה אומרת אותו דבר בשורה:
(a, b) -> a.length() - b.length().A lambda says the same in one line:(a, b) -> a.length() - b.length(). - Predicate בודק, Function ממיר, Consumer עושה משהו, ו-Supplier מייצר.A Predicate tests, a Function converts, a Consumer does something, and a Supplier produces.
- אפשר להרכיב:
negate(),andThen(...).They compose:negate(),andThen(...). totalמשתנה בתוך הלמבדה, ולכן הוא לא effectively final.totalchanges inside the lambda, so it isn't effectively final.- javac עוצר.javac stops.
local variables referenced from a lambda expression must be final or effectively final:local variables referenced from a lambda expression must be final or effectively final:
מונחיםTerms
- למבדהlambda: פונקציה קצרה בלי שם:
(a, b) -> a + b. Java הופכת אותה לעצם שמממש functional interface.A short nameless function:(a, b) -> a + b. Java turns it into an object implementing a functional interface. - functional interfacefunctional interface: interface עם מתודה מופשטת אחת בדיוק (כמו
Comparator,Runnable,Predicate). כל למבדה "נכנסת" לתוך interface כזה.@FunctionalInterfaceמבקש מ-javac לבדוק.An interface with exactly one abstract method (likeComparator,Runnable,Predicate). Every lambda "fits into" such an interface.@FunctionalInterfaceasks javac to check. - Predicate, Function, Consumer, SupplierPredicate, Function, Consumer, Supplier:
Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → כלום (accept).Supplier<T>: כלום → T (get).Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → nothing (accept).Supplier<T>: nothing → T (get). - method referencemethod reference: קיצור ללמבדה שרק קוראת למתודה:
String::lengthבמקוםs -> s.length(),System.out::println,Book::new.A shorthand for a lambda that only calls a method:String::lengthinstead ofs -> s.length(),System.out::println,Book::new. - effectively finaleffectively final: למבדה יכולה להשתמש במשתנה מקומי מבחוץ רק אם הוא לא משתנה אחרי שנקבע. אחרת javac עוצר.A lambda can use an outside local variable only if it never changes after it's set. Otherwise javac stops.
- Comparator.comparingComparator.comparing: בונה Comparator ממפתח:
Comparator.comparing(Book::year), ואפשר לשרשר.reversed()ו-.thenComparing(...).Builds a Comparator from a key:Comparator.comparing(Book::year), chaining.reversed()and.thenComparing(...). - למבדהlambda: פונקציה קצרה בלי שם:
(a, b) -> a + b. Java הופכת אותה לעצם שמממש functional interface.A short nameless function:(a, b) -> a + b. Java turns it into an object implementing a functional interface. - functional interfacefunctional interface: interface עם מתודה מופשטת אחת בדיוק (כמו
Comparator,Runnable,Predicate). כל למבדה "נכנסת" לתוך interface כזה.@FunctionalInterfaceמבקש מ-javac לבדוק.An interface with exactly one abstract method (likeComparator,Runnable,Predicate). Every lambda "fits into" such an interface.@FunctionalInterfaceasks javac to check. - Predicate, Function, Consumer, SupplierPredicate, Function, Consumer, Supplier:
Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → כלום (accept).Supplier<T>: כלום → T (get).Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → nothing (accept).Supplier<T>: nothing → T (get). - method referencemethod reference: קיצור ללמבדה שרק קוראת למתודה:
String::lengthבמקוםs -> s.length(),System.out::println,Book::new.A shorthand for a lambda that only calls a method:String::lengthinstead ofs -> s.length(),System.out::println,Book::new. - effectively finaleffectively final: למבדה יכולה להשתמש במשתנה מקומי מבחוץ רק אם הוא לא משתנה אחרי שנקבע. אחרת javac עוצר.A lambda can use an outside local variable only if it never changes after it's set. Otherwise javac stops.
- Comparator.comparingComparator.comparing: בונה Comparator ממפתח:
Comparator.comparing(Book::year), ואפשר לשרשר.reversed()ו-.thenComparing(...).Builds a Comparator from a key:Comparator.comparing(Book::year), chaining.reversed()and.thenComparing(...).
Cheatsheet
מחלקה קטנה → שורה אחתA small class → one line
List<String> words = new ArrayList<>(List.of("banana", "fig", "apple"));
words.sort((a, b) -> a.length() - b.length());
System.out.println(words);
words.sort(Comparator.comparing(String::length).reversed());
System.out.println(words);
words.forEach(w -> System.out.print(w.charAt(0)));
System.out.println();ארבעת ה-interfaces השימושייםThe four handy interfaces
Predicate<String> isLong = s -> s.length() > 4;
Function<String, Integer> len = String::length;
Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
Supplier<String> greeting = () -> "hello";
System.out.println(isLong.test("banana") + " " + isLong.negate().test("banana"));
System.out.println(len.apply("fig") + " " + len.andThen(n -> n * 10).apply("fig"));
shout.accept(greeting.get());שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
local variables referenced from a lambda expression must be | למבדה לא משנה משתנה מבחוץA lambda doesn't change an outside variable | local variables referenced from a lambda expression must be final or effectively final: הלמבדה מנסה לשנות את total.local variables referenced from a lambda expression must be final or effectively final: the lambda tries to change total. |
local variables referenced from a lambda expression must be | צייד באגים: משתנה בתוך למבדהBug hunter: a variable inside a lambda | local variables referenced from a lambda expression must be final or effectively final: אסור ללמבדה לשנות את total.local variables referenced from a lambda expression must be final or effectively final: the lambda may not change total. |