The java.util.function package
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
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
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)); }}Old way, 42: true Predicate, 42: true Predicate, 28: false
What this code does
PassCheckandPredicate<Integer>have the same shape: take a number, returnboolean. The same lambda text fills either one.- The built-in
Predicateneeds no extra file, and any library method that accepts aPredicateaccepts this rule. The method is calledtest, so the call ispassed.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.
Example 2 · The four core shapes in one program
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()); }}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. Supplierhas no input, so its lambda starts with(); here it gives the city to use when the form is left empty.Consumerreturns nothing, so its body is a statement, here aprintln.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. MethodR apply(T t). Example: marks to grade.Predicate<T>: takes and tests. Methodboolean test(T t). Example: did the student pass?Consumer<T>: takes only, returns nothing. Methodvoid accept(T t). Example: print a receipt line.Supplier<T>: returns only, takes nothing. MethodT get(). Example: give a default city.
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
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")); }}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 errorWhat this code does
testmust returnboolean, butname.length()is anint. 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, useFunction<String, Integer>instead.
Example 4 · Same lambda text, two different interfaces
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")); }}true true false
What this code does
- The lambda
s -> s.length() > 5has no type by itself. The variable on the left, its target type, decides which interface it becomes. - Both give the same answers, but
Predicateis the clearer choice for a yes/no rule: its name says "test", andtestreturns a plainbooleaninstead of a boxedBoolean.
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.
Error
ShapeFix.java:5: error: incompatible types: bad return type in lambda expression
Predicate<String> longName = s -> s.length();
int cannot be converted to booleanWhere 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
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); }}Allowed to sit the exam: [92, 75, 88]
92%
75%
88%
{A=[Rohan, Divya], B=[Kavya], C=[Arjun]}What this code does
removeIfcalls the predicate on every item and removes the ones that givetrue.forEachcalls the consumer on every item in order.computeIfAbsentcalls itsFunctiononly when the section is not in the map yet. The function makes the empty list, and.addputs 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 aFunction.
? 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