CodeGym /Courses /JAVA 25 SELF /Functional interfaces: Predicate, Consumer, Supplier, Fun...

Functional interfaces: Predicate, Consumer, Supplier, Function

JAVA 25 SELF
Level 49, Lesson 0
Available

1. A deeper look at functional interfaces

A functional interface is an interface that has EXACTLY one abstract (i.e., unimplemented) method. Thanks to this, Java understands: “aha, you can pass a lambda here!” or a method reference.

To avoid mistakes, such interfaces usually have the @FunctionalInterface annotation. It’s not mandatory, but if you add it and accidentally write a second abstract method, the compiler will complain immediately.

Example:

@FunctionalInterface
interface MyAction {
    void run();
}
MyAction action = () -> System.out.println("Hello from a lambda!");
action.run(); // Prints: Hello from a lambda!

Why is this useful?

  • Allows you to use lambda expressions and method references instead of creating anonymous classes (less boilerplate!).
  • Signals to the compiler that the interface is intended for functional programming.

Fun fact: The Java standard library already includes dozens of such interfaces—no need to reinvent the wheel!

2. Overview of standard functional interfaces

The java.util.function package offers dozens of functional interfaces. Let’s look at four of the most popular ones (they’re among the most widely used across Java).

Interface Takes Returns Typical use
Predicate<T>
T
boolean
Condition check (filtering)
Consumer<T>
T
void
Perform an action on an object
Supplier<T>
nothing
T
Produce/generate an object
Function<T, R>
T
R
Transform T to R

Predicate<T>

Description: A function that takes an object of type T and returns true or false. A typical example is list filtering. Key method — test.

Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("Java"));       // false
System.out.println(isLong.test("Functional")); // true

Consumer<T>

Description: Takes an object of type T and performs an action with it, returning nothing. Key method — accept.

Consumer<String> printer = s -> System.out.println("Printing: " + s);
printer.accept("Hello, world!"); // Printing: Hello, world!

Supplier<T>

Description: Takes nothing and returns an object of type T. You can think of it as a “generator” of values. Key method — get.

Supplier<Double> randomSupplier = () -> Math.random();
System.out.println(randomSupplier.get()); // For example, 0.1234567

Function<T, R>

Description: Takes an object of type T and returns an object of type R. A typical example is data transformation. Key method — apply.

Function<String, Integer> stringToLength = s -> s.length();
System.out.println(stringToLength.apply("Java")); // 4

Quickly: UnaryOperator, BinaryOperator, BiFunction

  • UnaryOperator<T> — the same as Function<T, T>: takes and returns the same type.
  • BinaryOperator<T> — the same as BiFunction<T, T, T>: takes two Ts, returns one T.
  • BiFunction<T, U, R> — takes two different types, returns a third.
UnaryOperator<Integer> square = x -> x * x;
BinaryOperator<Integer> sum = (a, b) -> a + b;
BiFunction<String, Integer, String> repeat = (s, n) -> s.repeat(n);

3. Usage examples

Let’s see how these interfaces appear in real tasks—especially in collections and the Stream API.

Passing to collection and Stream API methods

Example 1: Predicate and filtering

List<String> words = List.of("java", "stream", "lambda", "code");
List<String> longWords = words.stream()
    .filter(word -> word.length() > 4) // Predicate<String>
    .toList();
System.out.println(longWords); // [stream, lambda]

Example 2: Consumer and forEach

words.forEach(word -> System.out.println("Word: " + word)); // Consumer<String>

Example 3: Function and map

List<Integer> lengths = words.stream()
    .map(word -> word.length()) // Function<String, Integer>
    .toList();
System.out.println(lengths); // [4, 6, 6, 4]

Example 4: Supplier and value generation

Supplier<String> greetingSupplier = () -> "Hello, Java!";
System.out.println(greetingSupplier.get()); // Hello, Java!

Comparison with anonymous classes

Previously you had to write it like this:

Predicate<String> isShort = new Predicate<String>() {
    @Override
    public boolean test(String s) {
        return s.length() < 5;
    }
};

With lambdas it became much nicer:

Predicate<String> isShort = s -> s.length() < 5;

4. Practice: write lambda expressions for each interface

Let’s implement a small app—a list of users. Each user will be represented by the User class:

public class User {
    private final String name;
    private final int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

Create a list of users:

List<User> users = List.of(
    new User("Anna", 23),
    new User("Boris", 17),
    new User("Victoria", 31),
    new User("George", 15)
);

Predicate: filtering adults

Predicate<User> isAdult = user -> user.getAge() >= 18;
List<User> adults = users.stream()
    .filter(isAdult)
    .toList();

System.out.println("Adults: " + adults); // Adults: [Anna (23), Victoria (31)]

Consumer: printing users

Consumer<User> printUser = user -> System.out.println("User: " + user);
adults.forEach(printUser);

Supplier: generating users

Supplier<User> randomUserSupplier = () -> {
    String[] names = {"Dmitry", "Kate", "Alex"};
    int randomAge = 10 + (int)(Math.random() * 30);
    String randomName = names[(int)(Math.random() * names.length)];
    return new User(randomName, randomAge);
};

User randomUser = randomUserSupplier.get();
System.out.println("Random user: " + randomUser);

Function: getting a user's name

Function<User, String> getName = user -> user.getName();
List<String> names = users.stream()
    .map(getName)
    .toList();

System.out.println("Names: " + names); // Names: [Anna, Boris, Victoria, George]

5. Useful nuances

Usage in the Stream API: filter, map, forEach, etc.

Let’s put it all together and write a transformation pipeline:

users.stream()
     .filter(user -> user.getAge() >= 18)         // Predicate<User>
     .map(user -> user.getName().toUpperCase())    // Function<User, String>
     .forEach(name -> System.out.println("Adult: " + name)); // Consumer<String>

Result:

Adult: ANNA
Adult: VIKA

Cheat sheet: what to plug in where

Where it’s used Which interface to use Usage example
filter (Stream)
Predicate<T>
filter(u -> u.getAge() > 18)
map (Stream)
Function<T, R>
map(u -> u.getName())
forEach (Stream, List)
Consumer<T>
forEach(u -> System.out.println(u))
generate (Stream)
Supplier<T>
Stream.generate(() -> ...)

Why is it important to know about functional interfaces?

  • They underpin all lambda expressions in Java.
  • They let you write generic, reusable, and concise code.
  • They simplify working with collections, streams, and asynchronous tasks.

When to use which interface?

  • Predicate — when you need to check a condition (filtering, searching).
  • Consumer — when you need to do something with an object (print, write, send).
  • Supplier — when you need to obtain or generate an object (factories, generators).
  • Function — when you need to transform an object from one type to another.

6. Common mistakes when working with functional interfaces

Mistake #1: Choosing the wrong interface. Beginners sometimes confuse Predicate and Function—for example, they try to return a boolean from a Function instead of from a Predicate. Remember: Predicate always returns boolean, Function — any other type.

Mistake #2: Not using the standard interfaces. People often write their own interfaces like “Checker” with the method boolean check(T t) instead of using Predicate. It’s better to use the standard ones—they’re widely supported and make code clearer to other developers.

Mistake #3: The lambda is too complex. If a lambda turns into a mini-novel spanning 10 lines, you should extract it into a separate method or class. Lambdas are about brevity and readability.

Mistake #4: Missing the @FunctionalInterface annotation. If you write your own functional interface, don’t forget the annotation. It protects you from accidental mistakes (like adding a second abstract method).

Mistake #5: Using mutable state inside lambdas. If a lambda mutates external variables or collections, it can lead to unexpected bugs, especially when working with streams. It’s better to avoid side effects.

1
Task
JAVA 25 SELF, level 49, lesson 0
Locked
Analysis of Book Titles in the Fantasy Library 📚
Analysis of Book Titles in the Fantasy Library 📚
1
Task
JAVA 25 SELF, level 49, lesson 0
Locked
Managing game metrics in "Virtual Kingdom" 🎮
Managing game metrics in "Virtual Kingdom" 🎮
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION