Sub topic 2
Using Local Variables Inside Lambdas
This chapter covers four topics in order: using outside variables in a lambda, shortening lambdas with method references, defining your own functional interfaces, and using lambdas with lists and maps.
Using Local Variables Inside Lambdas
A local variable is a variable declared inside a method. A lambda can read a local variable from the method around it. This is called capturing the variable.
There is one rule. The variable must be effectively final, which means it is never changed after its first value is set.
import java.util.function.Consumer;
public class CaptureExample {
public static void main(String[] args) {
String greeting = "Hello"; // never changed, so effectively final
Consumer<String> greeter = name -> System.out.println(greeting + ", " + name);
greeter.accept("Ada"); // Hello, Ada
}
}If you add greeting = "Hi"; anywhere in this method, the code will not compile.
Method References: Shorter Lambdas
A method reference names an existing method with :: instead of writing a lambda. For example, s -> s.toUpperCase() can be written as String::toUpperCase.
| Kind | Example | Same as |
|---|---|---|
| Static method | `Integer::parseInt` | `s -> Integer.parseInt(s)` |
| Method of one object | `prefix::concat` | `s -> prefix.concat(s)` |
| Method of any object of a type | `String::toUpperCase` | `s -> s.toUpperCase()` |
| Constructor | `ArrayList::new` | `() -> new ArrayList<>()` |
Defining Your Own Functional Interfaces
You can write your own functional interface. A functional interface is an interface with exactly one abstract method. Mark it with @FunctionalInterface. If someone later adds a second abstract method, this annotation (a label the compiler checks) makes the compiler report an error.
@FunctionalInterface
interface Greeter {
String greet(String name);
}
public class GreeterDemo {
public static void main(String[] args) {
Greeter polite = name -> "Good day, " + name;
System.out.println(polite.greet("Sam")); // Good day, Sam
}
}Lambdas in Everyday Collection Code
Lists and maps have methods that take lambdas:
removeIfdeletes every item that matches a test.replaceAllchanges every item.forEachruns an action on every item.computeIfAbsentcreates a map value the first time a key is used.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Ann", "bob", "Cy", "dave"));
names.removeIf(n -> n.length() < 3); // [Ann, bob, dave]
names.replaceAll(String::toUpperCase); // [ANN, BOB, DAVE]
names.forEach(System.out::println);
Map<Integer, List<String>> byLength = new HashMap<>();
for (String n : names) {
byLength.computeIfAbsent(n.length(), k -> new ArrayList<>()).add(n);
}
System.out.println(byLength); // {3=[ANN, BOB], 4=[DAVE]}
}
}Exercise
This code does not compile: int count = 0; Runnable r = () -> System.out.println(count); count = 5; Why not?
Show answer
The lambda captures count, but count is changed later, so it is not effectively final. A lambda can only capture local variables that are never changed after their first value is set.
Exercise
Rewrite s -> Integer.parseInt(s) as a method reference.
Show answer
Integer::parseInt