AI Hints
Home›Java Tutorial›Lambdas, Functional Interfaces and Method References
Java · Lesson 101 of 120

Functional Interfaces

The shape of a function.

⏱ 2 min read▶ Video at 2:09:16🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Every lambda needs a type. That type is a functional interface, an interface with exactly one abstract method. Java has many ready made ones.

  • Lambdas need a type
  • One abstract method
  • Many ready-made

The four you will see most

Predicate takes a value, and answers true or false. Function takes a value, and returns another. Consumer takes a value, and returns nothing. And Supplier takes nothing, and gives back a value.

InterfaceTakesReturnsMethod
Predicate<T>Tbooleantest
Function<T, R>TRapply
Consumer<T>Tnothingaccept
Supplier<T>nothingTget

All four in use

Is long is a predicate, tested with test. Length is a function, used with apply. Shout is a consumer, used with accept. And dice is a supplier, called with get. Run it. Banana is long, but fig isn't. Java has four letters. Hello is shouted. And the dice gives a number from one to six.

Main.javajava
import java.util.function.*;
public class Main {
    public static void main(String[] args) {
        Predicate<String> isLong = s -> s.length() > 5;
        Function<String, Integer> length = s -> s.length();
        Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
        Supplier<Double> dice = () -> Math.floor(Math.random() * 6) + 1;

        System.out.println(isLong.test("banana") + " " + isLong.test("fig"));
        System.out.println(length.apply("Java"));
        shout.accept("hello");
        double roll = dice.get();
        System.out.println("Dice is 1 to 6? " + (roll >= 1 && roll <= 6));
    }
}
Output
true false
4
HELLO!
Dice is 1 to 6? true

Your own

You can write your own functional interface. Discount has one method, apply. Show accepts any discount, as a lambda. Each call passes different behaviour. Run it. Eighty, forty, and sixty five.

Main.javajava
public class Main {
    @FunctionalInterface
    interface Discount {
        double apply(double price);
    }

    static void show(String label, Discount d) {
        System.out.printf("%-10s %.2f%n", label, d.apply(80));
    }

    public static void main(String[] args) {
        show("None", p -> p);
        show("Half", p -> p / 2);
        show("Minus 15", p -> p - 15);
    }
}
Output
None       80.00
Half       40.00
Minus 15   65.00

Summary

A functional interface has one abstract method, and a lambda fills it in. Predicate, Function, Consumer, and Supplier are the most common. Next, an even shorter form, method references.

Key takeaways
  • One abstract method
  • Predicate, Function
  • Consumer, Supplier
Next up: Method References — point to a method