Sub topic 1
Refresher: Lambdas and Method References
Almost every stream operation takes a small piece of code as an argument. You will write that code as a lambda or a method reference. This chapter reviews both, so the stream chapters can focus on streams.
Why Streams Need Small Functions
A stream asks you questions like "Which items should I keep?" or "How should I change each item?" You answer by handing it a function. Before Java 8, you had to write a whole class to do that. Lambdas let you write the same function in one short line.
Functional Interfaces
A functional interface is an interface with exactly one abstract method. An abstract method is a method that has a name and parameters but no body. A lambda supplies that missing body.
Java ships many ready-made functional interfaces in the java.util.function package. You will see these often:
| Interface | Method | Takes | Returns | Typical use |
|---|---|---|---|---|
| `Predicate<T>` | `test` | one `T` | `boolean` | Keep or drop an item |
| `Function<T, R>` | `apply` | one `T` | an `R` | Change an item into something else |
| `Consumer<T>` | `accept` | one `T` | nothing | Do something with an item, like print it |
| `Supplier<T>` | `get` | nothing | a `T` | Create a value on demand |
| `BinaryOperator<T>` | `apply` | two `T` values | a `T` | Combine two items into one |
| `Comparator<T>` | `compare` | two `T` values | `int` | Decide sort order |
Comparator lives in java.util, not java.util.function, but it is still a functional interface.
Lambda Syntax
A lambda is an unnamed function written inline. It has three parts: parameters, an arrow ->, and a body.
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class LambdaBasics {
public static void main(String[] args) {
Predicate<String> isLong = s -> s.length() > 3;
Function<String, Integer> length = s -> s.length();
Consumer<String> greet = s -> System.out.println("Hello, " + s);
Supplier<String> message = () -> "Hi there";
System.out.println(isLong.test("bob")); // false
System.out.println(length.apply("alice")); // 5
greet.accept("carol"); // Hello, carol
System.out.println(message.get()); // Hi there
}
}Look at s -> s.length() > 3. The s is the parameter, and s.length() > 3 is the body. Java works out that s is a String from the variable type Predicate<String>. This is called type inference: the compiler figures out a type so you don't have to write it.
The Different Shapes of a Lambda
Lambdas come in a few shapes, depending on how many parameters they take and how long the body is.
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public class LambdaShapes {
public static void main(String[] args) {
// No parameters: empty parentheses are required
Supplier<Integer> answer = () -> 42;
// One parameter: parentheses are optional
Function<Integer, Integer> doubleIt = n -> n * 2;
// Two parameters: parentheses are required
BinaryOperator<Integer> add = (a, b) -> a + b;
// Explicit types: allowed, but rarely needed
BinaryOperator<Integer> multiply = (Integer a, Integer b) -> a * b;
// Block body: use braces, and write return yourself
Function<Integer, String> describe = n -> {
if (n % 2 == 0) {
return n + " is even";
}
return n + " is odd";
};
System.out.println(answer.get()); // 42
System.out.println(doubleIt.apply(5)); // 10
System.out.println(add.apply(3, 4)); // 7
System.out.println(multiply.apply(3, 4)); // 12
System.out.println(describe.apply(7)); // 7 is odd
}
}Capturing Variables: Effectively Final
A lambda can use variables from the code around it. This is called capturing a variable. There is one rule: the captured variable must be effectively final. That means you never change it after you first give it a value.
import java.util.function.Predicate;
public class CaptureExample {
public static void main(String[] args) {
int minimum = 3; // never changed, so it is effectively final
Predicate<String> longEnough = s -> s.length() >= minimum;
System.out.println(longEnough.test("hi")); // false
System.out.println(longEnough.test("hello")); // true
// minimum = 5; // If you uncomment this line, the lambda above
// // will not compile: minimum is no longer effectively final.
}
}The rule keeps lambdas predictable. A lambda might run later, or on another thread. If the variable could change, you could not tell which value the lambda would see.
Method References
Sometimes a lambda does nothing except call one method that already exists. For example, s -> s.toUpperCase() just calls toUpperCase. A method reference is a shorter way to write such a lambda. It uses a double colon: String::toUpperCase.
There are four kinds of method reference:
| Kind | Syntax | Same as this lambda |
|---|---|---|
| Static method | `Integer::parseInt` | `s -> Integer.parseInt(s)` |
| Method on a specific object | `System.out::println` | `x -> System.out.println(x)` |
| Instance method of any object of a type | `String::toUpperCase` | `s -> s.toUpperCase()` |
| Constructor | `ArrayList::new` | `() -> new ArrayList<>()` |
The third kind is the trickiest. With String::toUpperCase, the first parameter becomes the object the method is called on. With two parameters, String::compareTo means (a, b) -> a.compareTo(b).
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodRefs {
public static void main(String[] args) {
// 1. Static method
Function<String, Integer> parse = Integer::parseInt;
System.out.println(parse.apply("42") + 1); // 43
// 2. Method on a specific object (System.out)
Consumer<String> print = System.out::println;
print.accept("printed by a method reference");
// 3. Instance method of any String
Function<String, String> upper = String::toUpperCase;
System.out.println(upper.apply("java")); // JAVA
BiFunction<String, String, Boolean> sameText = String::equalsIgnoreCase;
System.out.println(sameText.apply("Java", "JAVA")); // true
// 4. Constructor
Supplier<List<String>> makeList = ArrayList::new;
List<String> list = makeList.get();
list.add("new item");
System.out.println(list); // [new item]
}
}A First Taste: Lambdas with Collections
Collections already accept lambdas, even without streams. The example below shows the same kind of arguments you will soon pass to stream operations.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CollectionPreview {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("carol", "bob", "alice", "dave"));
names.removeIf(name -> name.startsWith("d")); // a Predicate
names.sort(Comparator.comparing(String::length)); // a Function inside a Comparator
names.forEach(System.out::println); // a Consumer
// bob
// carol
// alice
}
}Comparator.comparing(String::length) builds a comparator that sorts by length. "carol" and "alice" have the same length, so they keep their original order. Java's list sort is stable: equal items do not swap places.
Common Errors
| Error | Cause | Fix |
|---|---|---|
| "local variables referenced from a lambda expression must be final or effectively final" | You changed a captured variable | Don't change it, or copy it into a new variable |
| "incompatible types: bad return type in lambda expression" | The body returns the wrong type | Check the interface's return type |
| "missing return statement" | A block body without `return` | Add `return`, or use an expression body |
| "invalid method reference" | The method's parameters don't match the interface | Write a lambda to see what is really being passed |
Exercise
Rewrite each lambda as a method reference: (a) s -> s.trim(), (b) x -> System.out.println(x), (c) s -> Integer.valueOf(s), (d) () -> new StringBuilder().
Show answer
(a) String::trim (instance method of any String). (b) System.out::println (method on a specific object). (c) Integer::valueOf (static method). (d) StringBuilder::new (constructor).
Exercise
Which functional interface fits each job? (a) Check whether a number is negative. (b) Turn a String into its length. (c) Add two integers together. (d) Print a value without returning anything.
Show answer
(a) Predicate<Integer>. (b) Function<String, Integer>. (c) BinaryOperator<Integer>. (d) Consumer<T> for the value's type.
Exercise
This code does not compile. Why? int count = 0; Runnable r = () -> count++;
Show answer
The lambda tries to change count, a captured local variable. Captured variables must be effectively final, so the compiler rejects any change to them from inside the lambda.