Lambdas ו-functional interfacesLambdas & functional interfaces
ביטויי למבדה, Function, Predicate, Consumer ו-Supplier, ו-method references.
Lambda expressions, Function, Predicate, Consumer and Supplier, and method references.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- למבדה: פונקציה קצרה בלי שם:
(a, b) -> a + b. Java הופכת אותה לעצם שמממש functional interface.lambda: A short nameless function:(a, b) -> a + b. Java turns it into an object implementing a functional interface. - functional interface: interface עם מתודה מופשטת אחת בדיוק (כמו
Comparator,Runnable,Predicate). כל למבדה "נכנסת" לתוך interface כזה.@FunctionalInterfaceמבקש מ-javac לבדוק.functional interface: An interface with exactly one abstract method (likeComparator,Runnable,Predicate). Every lambda "fits into" such an interface.@FunctionalInterfaceasks javac to check. - Predicate, Function, Consumer, Supplier:
Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → כלום (accept).Supplier<T>: כלום → T (get).Predicate, Function, Consumer, Supplier:Predicate<T>: T → boolean (test).Function<T, R>: T → R (apply).Consumer<T>: T → nothing (accept).Supplier<T>: nothing → T (get). - method reference: קיצור ללמבדה שרק קוראת למתודה:
String::lengthבמקוםs -> s.length(),System.out::println,Book::new.method reference: A shorthand for a lambda that only calls a method:String::lengthinstead ofs -> s.length(),System.out::println,Book::new. - effectively final: למבדה יכולה להשתמש במשתנה מקומי מבחוץ רק אם הוא לא משתנה אחרי שנקבע. אחרת javac עוצר.effectively final: A lambda can use an outside local variable only if it never changes after it's set. Otherwise javac stops.
- Comparator.comparing: בונה Comparator ממפתח:
Comparator.comparing(Book::year), ואפשר לשרשר.reversed()ו-.thenComparing(...).Comparator.comparing: Builds a Comparator from a key:Comparator.comparing(Book::year), chaining.reversed()and.thenComparing(...).
02מחלקה קטנה → שורה אחתA small class → one line
במפגש 24 כתבנו מחלקה שלמה בשביל Comparator. למבדה אומרת אותו דבר בשורה: (a, b) -> a.length() - b.length(). Comparator.comparing(String::length) עוד קצר יותר, ו-forEach מקבל למבדה שרצה על כל איבר.
In session 24 we wrote a whole class for a Comparator. A lambda says the same in one line: (a, b) -> a.length() - b.length(). Comparator.comparing(String::length) is shorter still, and forEach takes a lambda that runs on each item.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
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();
}
}[fig, apple, banana] [banana, apple, fig] baf
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03ארבעת ה-interfaces השימושייםThe four handy interfaces
Predicate בודק, Function ממיר, Consumer עושה משהו, ו-Supplier מייצר. אפשר להרכיב: negate(), andThen(...).
A Predicate tests, a Function converts, a Consumer does something, and a Supplier produces. They compose: negate(), andThen(...).
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
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());
}
}true false 3 30 HELLO!
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04למבדה לא משנה משתנה מבחוץA lambda doesn't change an outside variable
total משתנה בתוך הלמבדה, ולכן הוא לא effectively final. javac עוצר. בתרגיל 4 תתקנו עם לולאה רגילה (ובמפגש הבא, עם Stream).
total changes inside the lambda, so it isn't effectively final. javac stops. In exercise 4 you'll fix it with a plain loop (and next session, with a Stream).
למבדה לא משנה משתנה מבחוץ
A lambda doesn't change an outside variable
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("a", "bb", "ccc");
int total = 0;
words.forEach(w -> total += w.length());
System.out.println(total);
}
}Main.java:7: error: local variables referenced from a lambda expression must be final or effectively final
words.forEach(w -> total += w.length());
^
1 errorlocal 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.
These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.
צייד באגים: משתנה בתוך למבדה
Bug hunter: a variable inside a lambda
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("a", "bb", "ccc");
int total = 0;
words.forEach(w -> total += w.length());
System.out.println(total);
}
}Main.java:7: error: local variables referenced from a lambda expression must be final or effectively final
words.forEach(w -> total += w.length());
^
1 errorlocal 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.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06הצעד של היום בפרויקט מדףToday's step in the Shelf project
ל-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.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.