Sub topic 1
Why Lambdas? Passing Behavior with Anonymous Classes
Passing Behavior Before Java 8
Sometimes a method needs you to hand it some behavior, such as "compare two names and ignore upper and lower case." Before Java 8, the usual way to do this was an anonymous class. An anonymous class is a class with no name that you define and create in one place. It works, but it takes several lines to say one small thing. A lambda says the same thing in one line.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Charlie", "alice", "Bob"));
// Before Java 8: anonymous inner class
names.sort(new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.compareToIgnoreCase(b);
}
});
// Java 8+: the same behavior as a lambda
names.sort((a, b) -> a.compareToIgnoreCase(b));
System.out.println(names); // [alice, Bob, Charlie]
}
}Functional Interfaces: One Abstract Method
A functional interface is an interface with exactly one abstract method. An abstract method is a method that has no body yet. Comparator is a functional interface, and its one abstract method is compare. A lambda supplies the body for that one method. This is why you can only use a lambda in a place that expects a functional interface.
Writing Your First Lambda Expressions
A lambda expression is made of three parts: the parameters, an arrow ->, and a body.
- An expression body is a single expression, and its value is returned for you.
- A block body sits inside
{ }and needs its ownreturn. - You can leave the parameter types out, or write them in yourself.
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b; // expression body
Calculator multiply = (int a, int b) -> { // explicit types, block body
return a * b;
};
System.out.println(add.apply(2, 3)); // 5
System.out.println(multiply.apply(2, 3)); // 6
}
}How the Compiler Knows a Lambda's Type
A lambda has no type of its own. The compiler looks at where you put the lambda and finds the type expected there. That expected type is called the target type. In Calculator add = (a, b) -> a + b;, the target type is Calculator. From it, the compiler works out that a and b are int and that the result must be an int.
The Core Toolkit: Function, Predicate, Consumer, and Supplier
You often don't need to write your own interface, because the package java.util.function already has common ones.
| Interface | Takes | Returns | Method |
|---|---|---|---|
| `Function<T, R>` | one T | an R | `apply` |
| `Predicate<T>` | one T | boolean | `test` |
| `Consumer<T>` | one T | nothing | `accept` |
| `Supplier<T>` | nothing | a T | `get` |
| `UnaryOperator<T>` | one T | a T | `apply` |
| `BinaryOperator<T>` | two T | a T | `apply` |
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class BuiltInInterfaces {
public static void main(String[] args) {
Function<String, Integer> length = s -> s.length();
Predicate<Integer> isEven = n -> n % 2 == 0;
Consumer<String> printer = s -> System.out.println(s);
Supplier<String> greeting = () -> "Hello";
UnaryOperator<String> shout = s -> s.toUpperCase();
BinaryOperator<Integer> max = (a, b) -> Math.max(a, b);
System.out.println(length.apply("lambda")); // 6
System.out.println(isEven.test(4)); // true
printer.accept(greeting.get()); // Hello
System.out.println(shout.apply("hi")); // HI
System.out.println(max.apply(3, 7)); // 7
}
}Exercise
You need a lambda that takes a String and answers true or false depending on whether it is empty. Which interface fits, and what would the lambda look like?
Show answer
Predicate<String>, because it takes one value and returns a boolean. For example: Predicate<String> isEmpty = s -> s.isEmpty();