Skip to lesson

The java.util.function package

The java.util.function package is a set of ready-made functional interfaces. Each one describes a common shape of lambda, such as "takes a value and returns a result", so you almost never need to write your own interface for a lambda.

Recap: one abstract method, filled in by a lambda

A functional interface is an interface with exactly one abstract method, such as Predicate or Function. A lambda or method reference can be used wherever one is expected.

A functional interface is an interface with exactly one abstract method. A lambda is a short way to write the body of that one method, without writing a class.

The lambda itself has no type of its own. Java looks at where the lambda goes, such as a variable or a method parameter, and takes the interface from there. That place is called the target type. So n -> n >= 35 can be a pass check, a price filter or anything else whose one method takes a number and returns boolean.

The method name does not matter to the lambda. Only the shape matters: how many inputs the method takes, of what types, and what it returns.

Default and static methods do not count. An interface with one abstract method and ten default methods is still a functional interface.

Why Java ships ready-made interfaces

Before Java 8, every library wrote its own one-method interfaces, such as MarksFilter and FeeFilter, all taking a value and returning boolean. Java 8 added java.util.function with 43 general interfaces, so collections, Streams and your own code agree on one name per shape.

Example 1 · Your own interface versus the built-in one

BuiltInDemo.javaJava
import java.util.function.Predicate;
interface PassCheck {    boolean check(int marks);}
public class BuiltInDemo {    public static void main(String[] args) {        // before Java 8: write an interface for every rule        PassCheck oldWay = marks -> marks >= 35;        System.out.println("Old way, 42: " + oldWay.check(42));
        // Java 8 and later: the shape already has a name        Predicate<Integer> passed = marks -> marks >= 35;        System.out.println("Predicate, 42: " + passed.test(42));        System.out.println("Predicate, 28: " + passed.test(28));    }}
Output
Old way, 42: true
Predicate, 42: true
Predicate, 28: false

What this code does

  • PassCheck and Predicate<Integer> have the same shape: take a number, return boolean. The same lambda text fills either one.
  • The built-in Predicate needs no extra file, and any library method that accepts a Predicate accepts this rule. The method is called test, so the call is passed.test(42).

The old filters could not be mixed: a MarksFilter could not be passed where a FeeFilter was expected, even with the same body. Now a rule written once as a Predicate<Integer> works with removeIf, with your own methods and with every library that accepts a Predicate.

You do not need to learn all 43. Four core shapes cover most code, and the others are variations of these four for two inputs or for primitive values. Later lessons in this module cover those variations.

The four core shapes

Four generic interfaces cover most lambdas. In them, T is the input type and R is the result type.

The four core functional interfaces by what they take and give. Function<T, R>: takes T, gives R. Predicate<T>: takes T, gives boolean. Consumer<T>: takes T, gives nothing. Supplier<T>: takes nothing, gives T. Their methods are apply, test, accept and get.

Example 2 · The four core shapes in one program

FourShapesDemo.javaJava
import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;
public class FourShapesDemo {    public static void main(String[] args) {        // takes and returns: marks out of 50 to a percentage        Function<Integer, Double> toPercent = marks -> marks * 100.0 / 50;
        // takes and tests: is this a valid 6-digit PIN code?        Predicate<String> validPin = pin -> pin.length() == 6;
        // takes only: print one line of an attendance sheet        Consumer<String> markPresent = name -> System.out.println(name + " - present");
        Supplier<String> defaultCity = () -> "Bengaluru";
        System.out.println("41 out of 50 = " + toPercent.apply(41) + "%");        System.out.println("560001 valid? " + validPin.test("560001"));        System.out.println("5600 valid? " + validPin.test("5600"));        markPresent.accept("Kavya");        System.out.println("City: " + defaultCity.get());    }}
Output
41 out of 50 = 82.0%
560001 valid? true
5600 valid? false
Kavya - present
City: Bengaluru

What this code does

  • Each interface has its own method name: apply, test, accept, get. The lambda never names the method; you name it when you call it.
  • Supplier has no input, so its lambda starts with (); here it gives the city to use when the form is left empty. Consumer returns nothing, so its body is a statement, here a println.
  • Function<Integer, Double> lists the input type first and the result type second.

Read each one as a sentence about its method:

  • Function<T, R>: takes and returns. Method R apply(T t). Example: marks to grade.
  • Predicate<T>: takes and tests. Method boolean test(T t). Example: did the student pass?
  • Consumer<T>: takes only, returns nothing. Method void accept(T t). Example: print a receipt line.
  • Supplier<T>: returns only, takes nothing. Method T get(). Example: give a default city.
To pick one, ask two questions: does the lambda take an input, and what does it give back? The answers name the interface.

Pick the right one, or the compiler complains

The compiler checks the lambda against the method of its target type. A Predicate must return boolean, so a lambda that returns an int gives "bad return type in lambda expression".

Example 3 · Mistake: the lambda does not fit the shape

WrongShapeDemo.javaJava
import java.util.function.Predicate;
public class WrongShapeDemo {    public static void main(String[] args) {        Predicate<String> longName = name -> name.length();        System.out.println(longName.test("Aarav"));    }}
Sample compiler output
WrongShapeDemo.java:5: error: incompatible types: bad return type in lambda expression
        Predicate<String> longName = name -> name.length();
                                                        ^
    int cannot be converted to boolean
1 error

What this code does

  • test must return boolean, but name.length() is an int. The compiler checks every lambda against the one method of its target type.
  • Fix it by returning a yes/no answer, name -> name.length() > 4, or, if you really want the length, use Function<String, Integer> instead.

Example 4 · Same lambda text, two different interfaces

TargetTypeDemo.javaJava
import java.util.function.Function;import java.util.function.Predicate;
public class TargetTypeDemo {    public static void main(String[] args) {        Predicate<String> isLong = s -> s.length() > 5;        Function<String, Boolean> isLongToo = s -> s.length() > 5;
        System.out.println(isLong.test("Chennai"));        System.out.println(isLongToo.apply("Chennai"));        System.out.println(isLong.test("Goa"));    }}
Output
true
true
false

What this code does

  • The lambda s -> s.length() > 5 has no type by itself. The variable on the left, its target type, decides which interface it becomes.
  • Both give the same answers, but Predicate is the clearer choice for a yes/no rule: its name says "test", and test returns a plain boolean instead of a boxed Boolean.

One lambda text can fit two interfaces. s -> s.length() > 3 fits both Predicate<String> and Function<String, Boolean>. Choose the most specific one: a Predicate says "this is a yes/no rule" and returns a plain boolean, while the Function version boxes the answer into a Boolean object.

A Consumer lambda may call a method that returns a value, such as name -> list.add(name). The return value is simply thrown away, because accept returns void.

Fix the error

Fit the lambda to the shape

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

A Predicate must say yes or no.

import java.util.function.Predicate;
public class ShapeFix {
public static void main(String[] args) {
Predicate<String> longName = s -> s.length();
System.out.println(longName.test("Meera"));
}
}

Error

ShapeFix.java:5: error: incompatible types: bad return type in lambda expression
        Predicate<String> longName = s -> s.length();
    int cannot be converted to boolean

Where you already meet them

You have used these interfaces since the Collections section, perhaps without seeing their names. Every collection method that "takes a lambda" takes one of them.

Example 5 · You already use them: removeIf, forEach, computeIfAbsent

AlreadyUsingDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class AlreadyUsingDemo {    public static void main(String[] args) {        List<Integer> attendance = new ArrayList<>(List.of(92, 68, 75, 54, 88));
        // removeIf takes a Predicate<Integer>        attendance.removeIf(percent -> percent < 75);        System.out.println("Allowed to sit the exam: " + attendance);
        // forEach takes a Consumer<Integer>        attendance.forEach(percent -> System.out.println("  " + percent + "%"));
        // computeIfAbsent takes a Function<String, List<String>>        Map<String, List<String>> bySection = new TreeMap<>();        String[][] students = {{"A", "Rohan"}, {"B", "Kavya"}, {"A", "Divya"}, {"C", "Arjun"}};        for (String[] s : students) {            bySection.computeIfAbsent(s[0], section -> new ArrayList<>()).add(s[1]);        }        System.out.println(bySection);    }}
Output
Allowed to sit the exam: [92, 75, 88]
  92%
  75%
  88%
{A=[Rohan, Divya], B=[Kavya], C=[Arjun]}

What this code does

  • removeIf calls the predicate on every item and removes the ones that give true. forEach calls the consumer on every item in order.
  • computeIfAbsent calls its Function only when the section is not in the map yet. The function makes the empty list, and .add puts the name in it, so each section collects its own students.
  • list.removeIf(Predicate<? super E>): removes every item the predicate says yes to.
  • list.forEach(Consumer<? super T>): runs the consumer once for every item, in order.
  • map.computeIfAbsent(key, Function<? super K, ? extends V>): makes a value from the key only when the key is missing.
  • Comparator.comparing(Function<? super T, ? extends U>): the key extractor is a Function.
? super E means "E or a parent type of E". It lets a Predicate<Object> work on a list of String. For your own lambdas, simply think "a Predicate of the element type".

Next step

Check your understanding

12 quick questions