Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
The core java.util.function interfaces for the OCP 21 exam: Supplier, Consumer, BiConsumer, Predicate, BiPredicate, Function, BiFunction, UnaryOperator and BinaryOperator, their method names, type parameters and return types, how to pick the right one, and common generic mistakes.
kvi5hnuCode Sprout team member6 min readOn this page
Writing your own functional interface for every lambda would get tedious. The package java.util.function provides general-purpose ones, and the JDK's own APIs (collections, streams, Optional) use them everywhere. The exam expects you to know the nine core interfaces cold: their names, their method names, how many parameters they take, and what they return.
The core nine

| Interface | Abstract method | Parameters | Returns |
|---|---|---|---|
Supplier<T> | get() | 0 | T |
Consumer<T> | accept(T) | 1 | void |
BiConsumer<T, U> | accept(T, U) | 2 | void |
Predicate<T> | test(T) | 1 | boolean |
BiPredicate<T, U> | test(T, U) | 2 | boolean |
Function<T, R> | apply(T) | 1 | R |
BiFunction<T, U, R> | apply(T, U) | 2 | R |
UnaryOperator<T> | apply(T) | 1 | T |
BinaryOperator<T> | apply(T, T) | 2 | T |
The type parameter names follow a convention: T is the first input type, U the second, and R the result type. The prefix Bi always means two inputs. All the type arguments must be reference types: Supplier<int> doesn't compile, and article 50 covers the primitive versions.
Supplier: values from nothing
A Supplier produces a value without taking any input. It's typically used for factories and lazily created objects:
Supplier<LocalDate> today = LocalDate::now;
Supplier<StringBuilder> fresh = StringBuilder::new;
Supplier<ArrayList<String>> lists = ArrayList::new;
ArrayList<String> names = lists.get(); // a new, empty list on every call
Watch the nested generics. Supplier<ArrayList<String>> supplies lists of strings.
Printing a lambda object itself, as in System.out.println(fresh), doesn't call it. You get the default toString() of a JVM-generated class, something like Solution$$Lambda/0x...@1b6d3586. To get the value, call get().
Consumer and BiConsumer: do something, return nothing
A Consumer takes a value and returns nothing. It's used for side effects such as printing or storing:
Consumer<String> show = System.out::println;
show.accept("loaded"); // loaded
var stock = new HashMap<String, Integer>();
BiConsumer<String, Integer> put = stock::put; // put returns a value, which is discarded
put.accept("flour", 3);
System.out.println(stock); // {flour=3}
The two type parameters of BiConsumer may be different (as here) or the same.
Predicate and BiPredicate: yes or no
A Predicate tests a condition and returns a primitive boolean:
Predicate<String> blank = String::isBlank;
BiPredicate<String, String> hasSuffix = String::endsWith; // (s, suffix) -> s.endsWith(suffix)
System.out.println(blank.test(" ")); // true
System.out.println(hasSuffix.test("report.pdf", ".pdf")); // true
Predicates are the standard type for filters, as in list.removeIf(blank).
Function and BiFunction: transform
A Function turns one value into another, possibly of a different type. The last type parameter is always the result:
Function<String, Integer> len = String::length; // String in, Integer out
BiFunction<String, Integer, Character> charAt = String::charAt;
System.out.println(len.apply("croissant")); // 9
System.out.println(charAt.apply("croissant", 0)); // c
String::length returns int, which is autoboxed to Integer to fit R.
UnaryOperator and BinaryOperator: same type in and out
These are special cases of Function and BiFunction where every type is the same:
public interface UnaryOperator<T> extends Function<T, T> { }
public interface BinaryOperator<T> extends BiFunction<T, T, T> { }
They declare no new abstract method. They inherit apply, with the generics forcing input and output types to match:
UnaryOperator<String> upper = String::toUpperCase;
BinaryOperator<Integer> add = Integer::sum;
System.out.println(upper.apply("rye")); // RYE
System.out.println(add.apply(7, 5)); // 12
Since a UnaryOperator<String> is a Function<String, String>, you can assign it to a Function variable. The reverse needs a different object, because a Function<String, String> isn't a UnaryOperator.
Choosing the right interface
Ask three questions: how many inputs, is something returned, and is the result a boolean or the same type as the input?
| Situation | Best fit |
|---|---|
no input, returns a String | Supplier<String> |
takes a Long, returns nothing | Consumer<Long> |
takes a String, returns boolean | Predicate<String> |
takes a String, returns a Boolean object used as a value | Function<String, Boolean> |
takes two Integers, returns an Integer | BinaryOperator<Integer> (a BiFunction<Integer, Integer, Integer> also works, but is less specific) |
takes a String and an int, returns a char | BiFunction<String, Integer, Character> |
The type arguments in a declaration also give strong hints. With one type argument and a boolean result, it's a Predicate. With two type arguments and a boolean result, it's a BiPredicate, unless the second type argument is Boolean, in which case it may be a Function.
Spotting broken declarations
Function<List<String>> f = x -> x.get(0); // DOES NOT COMPILE: Function needs two type arguments
BiPredicate<String> both = (a, b) -> true; // DOES NOT COMPILE: BiPredicate needs two
UnaryOperator<Long> u = (Long l) -> 3.14; // DOES NOT COMPILE: must return a Long, not a double
UnaryOperator<String> n = String::length; // DOES NOT COMPILE: length() returns int, not String
Predicate<String> p = (a, b) -> true; // DOES NOT COMPILE: test takes one parameter
Predicate<String> q = s -> null; // DOES NOT COMPILE: null isn't a boolean
By contrast, Function<String, Boolean> f = s -> null; compiles, because Boolean is a reference type.
Other functional interfaces you'll meet
These JDK types are also functional interfaces, and they show up on the exam:
| Interface | Method | Covered in |
|---|---|---|
Runnable | void run() | concurrency (chapter 13) |
Callable<V> | V call() throws Exception | concurrency (chapter 13) |
Comparator<T> | int compare(T, T) | collections (chapter 9) |
Supplier<V> and Callable<V> have the same shape, except that call() may throw checked exceptions.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- The
java.util.functionpackage hasn't gained a single interface since Java 8. The 43 interfaces in it are the full current list.
Exam traps from this article
A complete example
A bakery order list uses all nine interfaces: a Supplier creates the list, a Consumer prints, predicates find bulk orders and name prefixes, functions calculate totals, operators format and add, and a BiConsumer aggregates quantities.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class Solution {
record Order(String item, int qty, int centsEach) { }
public static void main(String[] args) {
// Supplier<T>: T get() -- produces a value from nothing
Supplier<List<Order>> newList = ArrayList::new;
List<Order> orders = newList.get();
orders.add(new Order("bagel", 6, 120));
orders.add(new Order("muffin", 2, 250));
orders.add(new Order("baguette", 1, 300));
orders.add(new Order("bagel", 4, 120));
// Consumer<T>: void accept(T) -- uses a value, returns nothing
Consumer<Order> print = o -> System.out.println(" " + o.qty() + " x " + o.item());
System.out.println("orders:");
orders.forEach(print);
// Predicate<T>: boolean test(T)
Predicate<Order> bulk = o -> o.qty() >= 4;
// BiPredicate<T, U>: boolean test(T, U)
BiPredicate<Order, String> startsWith = (o, prefix) -> o.item().startsWith(prefix);
// Function<T, R>: R apply(T) -- converts one type to another
Function<Order, Integer> total = o -> o.qty() * o.centsEach();
// BiFunction<T, U, R>: R apply(T, U)
BiFunction<Order, Integer, Integer> discounted = (o, pct) -> total.apply(o) * (100 - pct) / 100;
// UnaryOperator<T>: T apply(T) -- same type in and out
UnaryOperator<String> label = String::toUpperCase;
// BinaryOperator<T>: T apply(T, T) -- combines two values of one type
BinaryOperator<Integer> add = Integer::sum;
// BiConsumer<T, U>: void accept(T, U) -- here map::put on a particular map
Map<String, Integer> qtyByItem = new TreeMap<>();
BiConsumer<String, Integer> addQty = (item, q) -> qtyByItem.merge(item, q, add);
int sum = 0;
for (Order o : orders) {
addQty.accept(o.item(), o.qty());
int cents = bulk.test(o) ? discounted.apply(o, 10) : total.apply(o);
sum = add.apply(sum, cents);
System.out.println(label.apply(o.item()) + (bulk.test(o) ? " (bulk -10%)" : "") + ": " + cents + " cents");
}
System.out.println("total: " + sum + " cents");
System.out.println("quantities: " + qtyByItem);
int bagOrders = 0;
for (Order o : orders) if (startsWith.test(o, "bag")) bagOrders++;
System.out.println("orders starting with 'bag': " + bagOrders);
}
}
Output:
orders:
6 x bagel
2 x muffin
1 x baguette
4 x bagel
BAGEL (bulk -10%): 648 cents
MUFFIN: 500 cents
BAGUETTE: 300 cents
BAGEL (bulk -10%): 432 cents
total: 1880 cents
quantities: {bagel=10, baguette=1, muffin=2}
orders starting with 'bag': 3
Points to notice:
ArrayList::newas aSuppliercreates the list. Each call toget()would create another one.discountedis aBiFunctionthat reuses thetotalfunction:6 × 120 = 720, minus 10% is648.Integer::sumworks as aBinaryOperator<Integer>, both to add the totals and as the merge function inMap.merge.addQtyis aBiConsumerthat captures the map. Quantities for the same item are combined, givingbagel=10.startsWithis aBiPredicatewith different input types: anOrderand aString.
Common questions
Why use BinaryOperator<Integer> instead of BiFunction<Integer, Integer, Integer>?
Both work. The operator is shorter and says the types are the same, so it's the better answer when the exam asks for the most specific interface.
Do I need to memorize every interface in java.util.function?
For the exam, you need these nine, the primitive variants and the convenience methods (next article).
Can I still write my own functional interfaces? Yes. Write one when a domain-specific name makes code clearer, or when you need checked exceptions or more than two parameters.
Summary
Supplier(get, no input),Consumer/BiConsumer(accept, returnsvoid),Predicate/BiPredicate(test, returnsboolean),Function/BiFunction(apply, returnsR).UnaryOperator<T>andBinaryOperator<T>extendFunctionandBiFunction, and force all types to be the same.TandUare inputs, andRis the result, always listed last.- Pick the interface from the number of inputs and the kind of result. Prefer the most specific fit.
- Generic arity mistakes, wrong return types and primitive type arguments are the usual compile errors.
Practice quiz
Test yourself with the built-in functional interfaces quiz: 10 exam-style questions with explanations.
Previous: Java Method References: Static, Bound, Unbound and Constructor (OCP 21)
Next: Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
Related reading
- Java Functional Interfaces: The Single Abstract Method Rule (OCP 21)
- Java Lambda Expressions: Syntax, Parameters and Bodies (OCP 21)
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
- Streaming XML Parsers in Java: SAX and StAX
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.