Java Functional Interface Convenience Methods and Primitive Specializations (OCP 21)
Combining functional interfaces for the OCP 21 exam: Predicate and, or, negate and not, Function andThen versus compose, Consumer andThen, identity, then the primitive interfaces for int, long, double and boolean, their renamed methods, and the To and Obj variants.
kvi5hnuCode Sprout team member6 min readOn this page
Functional interfaces have exactly one abstract method, but many of them also have default and static methods that combine or adapt instances. This article covers those convenience methods, then the large family of primitive functional interfaces that avoid boxing.
Convenience methods
| Interface | Method | Returns | Effect |
|---|---|---|---|
Predicate<T> | and(Predicate) | Predicate | both must be true (short-circuits) |
Predicate<T> | or(Predicate) | Predicate | either may be true (short-circuits) |
Predicate<T> | negate() | Predicate | the opposite |
Predicate (static) | not(Predicate) | Predicate | the opposite, as a static method (Java 11+) |
Predicate (static) | isEqual(Object) | Predicate | tests Objects.equals(target, x) |
Consumer<T> | andThen(Consumer) | Consumer | run this, then the other, with the same input |
Function<T, R> | andThen(Function) | Function | run this, then feed its result to the other |
Function<T, R> | compose(Function) | Function | run the other first, then feed its result to this |
Function (static) | identity() | Function | returns its input unchanged |
The two-argument interfaces have similar methods. BiPredicate has and, or and negate, BiConsumer has andThen, and BiFunction has andThen, which takes a one-argument Function for the result. They have no compose. Supplier has no convenience methods at all.
Predicate: and, or, negate
Instead of repeating conditions in new lambdas, build them from existing predicates:
Predicate<String> pdf = s -> s.endsWith(".pdf");
Predicate<String> draft = s -> s.startsWith("draft");
Predicate<String> finalPdf = pdf.and(draft.negate());
Predicate<String> notPdf = Predicate.not(pdf); // same as pdf.negate()
finalPdf.test("report.pdf"); // true
finalPdf.test("draft.pdf"); // false
The logic of pdf and draft now lives in one place each. Predicate.not is handy where a method reference is involved, as in Predicate.not(String::isBlank), because String::isBlank.negate() isn't valid syntax.
The type must match. Predicate<String>.and(Predicate<Integer>) doesn't compile.
Function: andThen versus compose
Both chain two functions. They differ in which one runs first:
Function<Integer, Integer> plusTen = x -> x + 10;
Function<Integer, Integer> half = x -> x / 2;
plusTen.andThen(half).apply(30); // (30 + 10) / 2 = 20
half.compose(plusTen).apply(30); // (30 + 10) / 2 = 20: same order
half.andThen(plusTen).apply(30); // 30 / 2 + 10 = 25

A way to remember it: f.andThen(g) reads left to right, f and then g. f.compose(g) is the mathematical f(g(x)), so the argument runs first. The types have to line up: the output of the first function must be an acceptable input for the second.
Consumer: andThen
Consumer.andThen also runs two operations in order, but nothing is passed from the first to the second. Both receive the same input:
Consumer<String> log = s -> System.out.print("[log " + s + "]");
Consumer<String> audit = s -> System.out.println("[audit " + s + "]");
log.andThen(audit).accept("notes.txt"); // [log notes.txt][audit notes.txt]
Primitive functional interfaces
Generic interfaces work only with objects, so Function<Integer, Integer> boxes and unboxes every value. For int, long and double, the JDK provides specialized versions that work with primitives directly. These matter a lot for streams in chapter 10.
boolean
There's only one: BooleanSupplier, with the method getAsBoolean(). There's no BooleanPredicate or BooleanFunction.
BooleanSupplier ready = () -> !queue.isEmpty();
ready.getAsBoolean();
int, long and double: equivalents of the core interfaces
Replace Int with Long or Double for the other two types:
| Interface | Method | Parameters | Returns |
|---|---|---|---|
IntSupplier | getAsInt() | 0 | int |
IntConsumer | accept(int) | 1 | void |
IntPredicate | test(int) | 1 | boolean |
IntFunction<R> | apply(int) | 1 | R |
IntUnaryOperator | applyAsInt(int) | 1 | int |
IntBinaryOperator | applyAsInt(int, int) | 2 | int |
There are three patterns to notice:
- When the return type is a primitive, the method gets an
Assuffix:getAsInt,applyAsInt,applyAsLong,applyAsDouble,getAsBoolean. Callingapplyon anIntUnaryOperatordoesn't compile. - When the return is an object (
IntFunction<R>) orvoid/boolean, the original names stay:apply,accept,test. - Generics disappear wherever the type name already says what the type is.
IntFunction<R>keeps only the result type.
There's no IntBiFunction, IntBiPredicate or IntBiConsumer.
Conversions to and from primitives
| Interface | Method | Parameters | Returns |
|---|---|---|---|
ToIntFunction<T> (also ToLong…, ToDouble…) | applyAsInt(T) | 1 (T) | int |
ToIntBiFunction<T, U> (also ToLong…, ToDouble…) | applyAsInt(T, U) | 2 (T, U) | int |
DoubleToIntFunction, DoubleToLongFunction, IntToDoubleFunction, IntToLongFunction, LongToDoubleFunction, LongToIntFunction | applyAsX(…) | 1 primitive | another primitive |
ObjIntConsumer<T> (also ObjLong…, ObjDouble…) | accept(T, int) | 2 (T, primitive) | void |
The naming tells you everything. ToX means the result is the primitive X, XToY converts one primitive to another, and ObjX takes an object plus a primitive.
Reading the clues
var d = 1.0;
_______ f = x -> 1;
int result = f.applyAsInt(d);
The method is applyAsInt, the argument is a double, and there's no generic type in the blank. DoubleToIntFunction fits. ToIntFunction<Double> also works, through autoboxing, if you add the type argument.
Primitive interfaces have their own convenience methods. IntPredicate has and, or and negate, IntUnaryOperator has andThen, compose and identity, and IntConsumer has andThen. They accept only matching primitive interfaces.
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).
Predicate.not(Java 11) is the newest convenience method you're likely to see. Everything in the tables here exists in Java 21 and 25.
Exam traps from this article
A complete example
A file list is filtered with combined predicates, file names are measured with andThen and compose, consumers are chained, and a set of primitive interfaces sums odd squares, converts and prints without boxing.
import java.util.List;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.function.DoubleToIntFunction;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.ObjIntConsumer;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;
public class Solution {
public static void main(String[] args) {
List<String> files = List.of("report.pdf", "photo.png", "notes.txt", "draft.pdf", "logo.png");
// Predicate: and, or, negate, and the static Predicate.not
Predicate<String> pdf = s -> s.endsWith(".pdf");
Predicate<String> png = s -> s.endsWith(".png");
Predicate<String> draft = s -> s.startsWith("draft");
Predicate<String> finalPdf = pdf.and(draft.negate());
Predicate<String> image = png.or(s -> s.endsWith(".jpg"));
for (String f : files) {
System.out.printf("%-11s finalPdf=%-5b image=%-5b notPdf=%b%n",
f, finalPdf.test(f), image.test(f), Predicate.not(pdf).test(f));
}
// Function: andThen runs this first, compose runs the argument first
Function<String, String> stripExt = s -> s.substring(0, s.indexOf('.'));
Function<String, Integer> length = String::length;
Function<String, Integer> nameLength = stripExt.andThen(length);
Function<String, Integer> sameThing = length.compose(stripExt);
System.out.println("name lengths: " + nameLength.apply("report.pdf") + " " + sameThing.apply("logo.png"));
// Consumer: andThen passes the SAME argument to both
Consumer<String> log = s -> System.out.print("[log " + s + "]");
Consumer<String> audit = s -> System.out.println("[audit " + s + "]");
log.andThen(audit).accept("notes.txt");
// Primitive specializations: no boxing, method names change
IntPredicate even = n -> n % 2 == 0;
IntUnaryOperator square = n -> n * n;
IntBinaryOperator plus = Integer::sum;
IntFunction<String> stars = n -> "*".repeat(n);
ToIntFunction<String> size = String::length;
DoubleToIntFunction floor = d -> (int) Math.floor(d);
ObjIntConsumer<String> repeat = (s, n) -> System.out.println(s.repeat(n));
BooleanSupplier ready = () -> !files.isEmpty();
int total = 0;
for (int i = 1; i <= 5; i++) {
if (even.negate().test(i)) total = plus.applyAsInt(total, square.applyAsInt(i));
}
System.out.println("sum of odd squares 1..5: " + total);
System.out.println("square then +1: " + square.andThen(n -> n + 1).applyAsInt(4));
System.out.println("stars: " + stars.apply(size.applyAsInt("png")));
System.out.println("floor 7.9: " + floor.applyAsInt(7.9));
repeat.accept("ab", 3);
System.out.println("ready? " + ready.getAsBoolean());
}
}
Output:
report.pdf finalPdf=true image=false notPdf=false
photo.png finalPdf=false image=true notPdf=true
notes.txt finalPdf=false image=false notPdf=true
draft.pdf finalPdf=false image=false notPdf=false
logo.png finalPdf=false image=true notPdf=true
name lengths: 6 4
[log notes.txt][audit notes.txt]
sum of odd squares 1..5: 35
square then +1: 17
stars: ***
floor 7.9: 7
ababab
ready? true
Points to notice:
finalPdfispdf.and(draft.negate()), sodraft.pdffails andreport.pdfpasses.stripExt.andThen(length)andlength.compose(stripExt)are the same pipeline written in two directions.log.andThen(audit)printsnotes.txttwice, because both consumers get the original input.even.negate()is anIntPredicate.1 + 9 + 25 = 35.square.andThen(n -> n + 1)squares4first, giving17.IntFunction<String>returns an object throughapply,ToIntFunction<String>returns anintthroughapplyAsInt, andObjIntConsumertakes both an object and anint.
Common questions
Why bother with primitive interfaces?
Boxing every value creates objects and costs time. In large loops and streams, IntUnaryOperator and friends avoid that overhead. They also make the intended type obvious.
Do I need to memorize every primitive interface?
Learn the naming rules: the type prefix, To, XToY, Obj, and the As method names. With those, you can work out the rest.
Is Predicate.not on the exam?
It's part of the Java 21 API and commonly used with method references. Know that it's a static method that negates its argument.
Summary
Predicatehasand,or,negateand the staticnotandisEqual.Consumer.andThenruns both consumers on the same input.Function.andThenruns this function first, andcomposeruns the argument first.Function.identity()returns its input.BooleanSupplier.getAsBoolean()is the only boolean functional interface.Int,LongandDoubleversions exist for the supplier, consumer, predicate, function, unary operator and binary operator. Primitive return types useAsmethod names.ToXFunction,ToXBiFunction,XToYFunctionandObjXConsumerconvert between objects and primitives.
Practice quiz
Test yourself with the convenience and primitive interfaces quiz: 10 exam-style questions with explanations.
Previous: Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
Next: Java Lambda Variables: Parameters, Locals and Effectively Final Captures (OCP 21)
Related reading
- Java Built-in Functional Interfaces: Supplier, Consumer, Predicate, Function and Operators (OCP 21)
- 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

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.