Summary - Lambda expressions
- Java course
- Intermediate
- Lesson 105/116
- 5 min
Combine lambda and method reference to write a sorting helper.
Summary - Lambda expressions
This group covered lambda expressions and method references. Lambda syntax: (parameters) -> body. Single parameter: parentheses optional; block body: return required. A lambda is assigned only to functional interfaces (one abstract method).
A method reference Class::method shortens lambdas whose body is a single method call. forEach expects a Consumer; it is the functional counterpart of the for-each loop. Comparator lambdas make sorting modern and readable.
Practice Lambda exercise: forEach and sort
Declare List<String> names = new ArrayList<>();; add "Ayşe", "Alex", "Mehmet". Sort alphabetically with names.sort((a, b) -> a.compareTo(b));. Print with a lambda using names.forEach(s -> System.out.println(s));.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add 3 names, sort alphabetically, print with forEach lambda
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
names.add("Mehmet");
names.sort((a, b) -> a.compareTo(b));
names.forEach(s -> System.out.println(s));
}
}Expected output
Alex Ayşe Mehmet
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the lambda concepts
| Term | Meaning |
|---|---|
() -> ... |
No-arg lambda |
s -> ... |
Single parameter |
Class::method |
Method reference |
(a, b) -> a - b |
Comparator lambda |
2 Which one is a method reference?
- (a, b) -> a + b
- s -> s.length()
- Math::abs Correct answer
- () -> new Object()
Explanation: Math::abs is a static method reference; it uses the :: token.
3 Match lambda vs method reference
| Term | Meaning |
|---|---|
-> |
Lambda arrow |
:: |
Method reference |
Runnable |
No-arg target |
Comparator |
Sorting target |