Sub topic 17
Functional Interfaces and Lambdas
Earlier chapters showed that an interface lists methods, and a class must write the bodies for them. Writing a whole class just to supply one short method body can feel like a lot of typing. Java has a shortcut for this case. When an interface has exactly one abstract method, you can implement it with a lambda expression, which is a short piece of code that acts as the method body.
This chapter explains what makes an interface "functional," how to write lambdas, and the rules that trip up beginners.
What Is a Functional Interface?
A functional interface is an interface with exactly one abstract method. An abstract method is a method with no body that implementers must supply.
The one-method rule is what makes lambdas possible. A lambda has no method name. Java can only work out which method it implements when there is just one to choose from.
Here is the simplest example:
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println(add.apply(3, 4)); // prints: 7
System.out.println(multiply.apply(3, 4)); // prints: 12
}
}Calculator has one abstract method, apply. The line (a, b) -> a + b is a lambda. It means "take a and b, and give back a + b." Java sees that the variable type is Calculator, so it treats the lambda as the body of apply.
You never wrote a class named Adder or Multiplier. Java creates the object for you behind the scenes.
The @FunctionalInterface Annotation
An annotation is a label that starts with @ and gives extra information to the compiler. @FunctionalInterface tells the compiler: "This interface must have exactly one abstract method. Warn me if it does not."
The annotation is optional. An interface with one abstract method is functional even without it. The label protects you from mistakes later. Suppose a teammate adds a second abstract method:
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
// int undo(int a, int b); // adding this line causes a compile error
}
public class Main {
public static void main(String[] args) {
Calculator subtract = (a, b) -> a - b;
System.out.println(subtract.apply(10, 4)); // prints: 6
}
}If you remove the // in front of undo, the code stops compiling. The compiler reports that it found more than one abstract method. Without the annotation, the error would show up somewhere else: at every lambda that uses Calculator. That is harder to track down.
What Counts Toward the "One Method" Rule
Only abstract methods count. An interface can have other methods and still be functional:
| Kind of method | Counts toward the limit? | Why |
|---|---|---|
| Abstract method | Yes | Implementers must supply it |
| Default method | No | It already has a body |
| Static method | No | It belongs to the interface, not to objects |
| Private method | No | It already has a body and is hidden |
| `equals`, `hashCode`, `toString` declared abstractly | No | Every object already gets these from `Object` |
The last row is an edge case. Some interfaces in the Java library re-declare boolean equals(Object o); to add documentation. Every class already has equals, so this does not count as a second method.
Here is a functional interface with a default method:
@FunctionalInterface
interface Greeter {
String greet(String name);
default String greetLoudly(String name) {
return greet(name).toUpperCase();
}
}
public class Main {
static void welcome(Greeter g, String name) {
System.out.println(g.greet(name));
}
public static void main(String[] args) {
Greeter polite = name -> "Hello, " + name + ".";
Greeter friendly = name -> {
String first = name.substring(0, 1).toUpperCase();
return "Hey " + first + name.substring(1) + "!";
};
welcome(polite, "Ana"); // prints: Hello, Ana.
welcome(friendly, "ben"); // prints: Hey Ben!
System.out.println(polite.greetLoudly("Ana")); // prints: HELLO, ANA.
}
}This example shows two new ideas. First, welcome takes a Greeter as a parameter, so you can pass different behavior into the same method. Second, the lambda gets the default method greetLoudly for free, because the lambda object is still a Greeter.
Lambda Syntax Forms
A lambda has three parts: the parameters, the arrow ->, and the body. The table shows the common shapes.
| Form | Example | When to use |
|---|---|---|
| No parameters | `() -> System.out.println("hi")` | Method takes nothing |
| One parameter | `name -> "Hi " + name` | Parentheses are optional for one parameter |
| Several parameters | `(a, b) -> a + b` | Parentheses are required |
| Typed parameters | `(int a, int b) -> a + b` | When you want the types spelled out |
| Block body | `x -> { int y = x * 2; return y; }` | More than one statement |
There is one rule for the block body. If the method returns a value, you must write return inside the braces. A single-expression body like a + b returns its value without return.
The target type is the type the lambda is assigned to or passed as. A lambda on its own has no type, so var f = x -> x; does not compile.
Lambdas Compared with Anonymous Classes
Before Java 8, people used an anonymous class, a class with no name that is written and used in one place. Both versions below do the same job:
@FunctionalInterface
interface Checker {
boolean test(int n);
}
public class Main {
public static void main(String[] args) {
Checker oldStyle = new Checker() {
@Override
public boolean test(int n) {
return n % 2 == 0;
}
};
Checker newStyle = n -> n % 2 == 0;
System.out.println(oldStyle.test(4)); // prints: true
System.out.println(newStyle.test(7)); // prints: false
}
}The lambda is one line. An anonymous class is still useful when the interface has several abstract methods, or when you need fields inside the object.
Using Outside Variables
A lambda can read local variables from the method around it. The variable must be effectively final, which means it is never changed after it is first given a value.
@FunctionalInterface
interface Checker {
boolean test(int n);
}
public class Main {
public static void main(String[] args) {
int limit = 10; // never changed, so effectively final
Checker small = n -> n < limit;
System.out.println(small.test(3)); // prints: true
System.out.println(small.test(15)); // prints: false
// limit = 20; // uncommenting this breaks the lambda above
}
}Built-in Functional Interfaces
You do not always need to write your own. The package java.util.function has ready-made ones:
| Interface | Abstract method | Meaning |
|---|---|---|
| `Predicate<T>` | `boolean test(T t)` | Yes or no question about a value |
| `Function<T, R>` | `R apply(T t)` | Turn a T into an R |
| `Consumer<T>` | `void accept(T t)` | Do something with a value |
| `Supplier<T>` | `T get()` | Produce a value |
import java.util.function.Function;
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> isEmpty = s -> s.isEmpty();
Function<String, Integer> length = s -> s.length();
System.out.println(isEmpty.test("")); // prints: true
System.out.println(length.apply("Java")); // prints: 4
}
}Write your own interface when a clear name like Calculator or Greeter makes your code easier to read.
Exercises
Exercise
An interface has one abstract method, two default methods, and one static method. Is it a functional interface? Explain.
Show answer
Yes. Only abstract methods count toward the rule. Default and static methods already have bodies, so the interface still has exactly one abstract method.
Exercise
Write a functional interface named Formatter with a method String format(double value). Then write a lambda that returns the value with a dollar sign in front, and print the result for 9.5.
Show answer
Declare "@FunctionalInterface interface Formatter { String format(double value); }". In main, write "Formatter money = v -> "$" + v;" and then "System.out.println(money.format(9.5));". It prints $9.5.
Exercise
Why does this code fail to compile? int count = 0; Checker c = n -> n > count; count++;
Show answer
The lambda uses count, but count is changed later by count++. That means count is not effectively final, and lambdas can only use local variables that never change after they get their first value.