Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Show how to compose functions with Function.andThen and compose, and predicates with and, or and negate. What is the difference between f.andThen(g) and f.compose(g)?

f.andThen(g) builds a function that applies f first and then g, so it computes x -> g(f(x)), while f.compose(g) applies g first and then f, computing x -> f(g(x)). Predicates combine with and, or and negate, for example isBlank.negate().and(s -> s.length() < 50), and Predicate.not(String::isBlank), added in Java 11, lets us negate a method reference directly. Comparator.comparing(...).thenComparing(...) is the same idea applied to sorting.

Why this question is asked

Function composition means building a new function out of smaller ones, the way we build a sentence out of words. Java's functional interfaces include default methods for exactly this, and they turn up everywhere: in stream filters, in validation, in sorting and in small data pipelines. Interviewers ask this to check that we know the methods, and especially that we do not mix up andThen and compose, which differ only in order. In this answer, we will recap Function and Predicate, compare andThen and compose with concrete numbers, combine predicates, see why Predicate.not exists, and look at Comparator as another example of composition.

1A Quick Recap of Function and Predicate

Function<T, R> is a functional interface with one abstract method, R apply(T t): it takes a value and returns another. Predicate<T> has boolean test(T t): it takes a value and answers yes or no. Both have default methods that return new functions built from existing ones, so composing them never changes the originals; it always creates a new object that calls them in some order.

2AndThen Versus compose

The two methods differ only in which function runs first. Using two simple functions makes the difference easy to see.

Java
Function<Integer, Integer> plusOne = x -> x + 1;
Function<Integer, Integer> timesTwo = x -> x * 2;
plusOne.andThen(timesTwo).apply(5); // 12: plusOne first, (5 + 1) * 2
plusOne.compose(timesTwo).apply(5); // 11: timesTwo first, (5 * 2) + 1
Function<String, String> strip = String::strip;
Function<String, Integer> length = String::length;
strip.andThen(length).apply(" hi "); // 2: strip, then measure
length.compose(strip).apply(" hi "); // 2: the same pipeline written from the other end
Order of execution for input 5
ExpressionRuns firstThenResult
plusOne.andThen(timesTwo)plusOne: 6timesTwo: 1212
plusOne.compose(timesTwo)timesTwo: 10plusOne: 1111
andThen: the receiver first. compose: the argument first.

A good way to remember it: andThen reads in the order things happen, "do f, and then g", which is why most people find it more natural. compose reads like mathematical notation, where f(g(x)) is written with f outside but g runs first. Notice also that types must line up: in strip.andThen(length), the output of strip (String) must be the input of length (String), and the result is a Function<String, Integer>.

3Combining Predicates With and, or and negate

Predicates combine with boolean logic. and requires both to be true, or requires at least one, and negate flips the answer.

Java
Predicate<String> isBlank = String::isBlank;
Predicate<String> validTitle = isBlank.negate().and(s -> s.length() < 50);
validTitle.test("Quarterly report"); // true: not blank and short
validTitle.test(" "); // false: blank
validTitle.test("x".repeat(60)); // false: too long
Predicate<String> isDraft = s -> s.startsWith("DRAFT");
validTitle.or(isDraft).test(" "); // false: neither is true
validTitle.and(isDraft.negate()).test("DRAFT plan"); // false: it is a draft

and and or short-circuit just like && and ||: if the first predicate already decides the answer, the second is not called. That matters when the second predicate is expensive or would fail on some inputs, so we put the cheap or guarding check first, as in notNull.and(s -> s.length() < 50).

4Why Predicate.not Exists

There is one awkward case. We often want to filter with the opposite of a method reference, such as keeping only non-blank strings. A method reference has no type until the compiler knows what interface it should become, so we cannot call negate() on it directly.

Java
names.stream().filter(String::isBlank.negate()); // does not compile: no target type yet
names.stream().filter(s -> !s.isBlank()); // works, but loses the method reference
names.stream().filter(Predicate.not(String::isBlank)); // Java 11+: reads naturally
List.of("Ana", " ", "Bo").stream()
.filter(Predicate.not(String::isBlank))
.toList(); // [Ana, Bo]

Predicate.not is a static method that takes a predicate and returns its negation. Because it declares its parameter type, the compiler knows String::isBlank must become a Predicate<String>, and the code reads almost like English.

5Comparator: Composition for Sorting

Comparators are another everyday example of composition. Comparator.comparing builds a comparator from a key-extracting function, and thenComparing adds a tie-breaker used only when the first comparison finds two elements equal.

Java
record Employee(String department, String name, int salary) {}
Comparator<Employee> order = Comparator
.comparing(Employee::department) // first by department
.thenComparing(Employee::salary, Comparator.reverseOrder()) // then highest salary first
.thenComparing(Employee::name); // then by name
List<Employee> sorted = staff.stream().sorted(order).toList();
// [Employee[department=Ops, name=Kai, salary=90], Employee[department=Ops, name=Lee, salary=70],
// Employee[department=Sales, name=Ana, salary=80], ...]

Each method returns a new Comparator that wraps the previous one, exactly like andThen wraps functions. Comparator also has reversed() to flip the whole order, and nullsFirst and nullsLast to decide where null keys go. This style replaced long hand-written compare methods with nested if statements, and it is one of the clearest wins of functional composition in Java.

6Follow-up questions

Does composing functions have a performance cost?

A small one: each composed function is an extra object and an extra call. In practice the JIT compiler usually inlines these small calls, so the cost is negligible compared with the work the functions do. It only matters in extremely hot loops, where a single hand-written lambda may be marginally faster.

Is there an identity function to start a composition?

Yes, Function.identity() returns a function that returns its input. It is useful as the starting value when reducing a list of functions with andThen, for example steps.stream().reduce(Function.identity(), Function::andThen).

Can I compose BiFunctions?

BiFunction has andThen, which applies a Function to its result, but no compose, because it would need two inputs from one function. For other shapes we write a small lambda that calls the pieces in the order we want.

7Conclusion

In this answer, we saw that f.andThen(g) runs f first and then g, giving x -> g(f(x)), while f.compose(g) runs g first, giving x -> f(g(x)). Predicates combine with and, or and negate, which short-circuit like && and ||, and Predicate.not lets us negate a method reference such as String::isBlank. Comparator.comparing with thenComparing applies the same composition idea to sorting, building a multi-key order from small, readable parts.

What to say in the interviewAbout 70 seconds aloud

Open with

Function has two default methods for composition. f.andThen(g) gives a new function that applies f first and then g, so x goes to g of f of x. f.compose(g) is the opposite: g runs first, then f, so x goes to f of g of x.

Then, if they want more

With plusOne and timesTwo on 5, andThen gives 12, because it's 5 plus 1, then doubled, and compose gives 11, because it's 5 doubled, then plus 1. I remember it as andThen reading in execution order and compose reading like math notation.

Predicates combine with and, or and negate, which return new predicates and short-circuit like the boolean operators, so I put cheap or guarding checks first. For example isBlank.negate().and(s -> s.length() < 50) accepts a non-blank title under fifty characters.

One awkward case is negating a method reference: String::isBlank.negate() doesn't compile because a method reference has no type until it has a target. Predicate.not, added in Java 11, solves that, so filter(Predicate.not(String::isBlank)) reads naturally. Comparator is another everyday example: Comparator.comparing(Employee::department).thenComparing(Employee::salary, reverseOrder()) builds a multi-key sort from small pieces, each method returning a new comparator that wraps the previous one.

About this answer

Last updated
12 November 2026
Versions it names
Java 11
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Show how to compose functions with Function.andThen and compose, and predicates with...": https://scrivio-interview-library.netlify.app/java/functional-design/77d82920ef/