ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume III
  5. Standard Interfaces
Book 1 · Volume III — Functional Java, Streams & Modern Java · Topic 2.1

Standard Interfaces

Predicate, Function, Consumer and Supplier

9 min readStage 1 · Foundations11 interview questions
Prerequisites
Chapter 1 · B1V2 2.3 PECS
Covers
Predicate · Function · Consumer · Supplier
Related
2.2 Specialized Interfaces · 3.1 Method References · Chapter 4 Streams · 5.2 Optional Operations
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers

1Concept / Definition

java.util.function provides ready-made functional interfaces so that APIs do not each invent their own. Four of them are the core shapes from which the rest are derived: a Predicate answers a yes/no question about a value, a Function transforms a value into another, a Consumer does something with a value and returns nothing, and a Supplier produces a value from nothing.

Input and output of the four core interfaces
Figure 1 — Input and output of the four core interfaces
How the 43 interfaces of java.util.function are organised
Figure 2 — How the 43 interfaces of java.util.function are organised

2Why It Exists

Before Java 8, every library defined its own callback types — Filter, Transformer, Callback — so behaviour written for one library could not be passed to another. A shared, standard set lets lambdas flow between the JDK, frameworks and application code, and lets the JDK provide useful combinators (and, andThen, identity) once for everyone.

3Core Concepts

Typical uses of the core interfaces
Figure 3 — Typical uses of the core interfaces

Predicate

Predicate<T> has the method boolean test(T t). It is used wherever a condition is needed: Stream.filter, Collection.removeIf, Optional.filter, anyMatch. Predicates compose with the default methods and, or and negate, which short-circuit like && and ||, and with the statics Predicate.not(p) (Java 11) — handy with method references, as in filter(Predicate.not(String::isBlank)) — and Predicate.isEqual(target).

Building compound conditions from simple predicates
Figure 4 — Building compound conditions from simple predicates

Function

Function<T, R> has R apply(T t) and is the general transformation: Stream.map, Map.computeIfAbsent, Comparator.comparing, Optional.map, Collectors.groupingBy. Functions compose: f.andThen(g) applies f then g; f.compose(g) applies g then f; Function.identity() returns its input and is common in toMap(Function.identity(), …). Signatures in the JDK use wildcards — Function<? super T, ? extends R> — following PECS (B1V2 2.3).

andThen and compose apply the same functions in opposite orders
Figure 5 — andThen and compose apply the same functions in opposite orders

Consumer

Consumer<T> has void accept(T t). It exists for its side effects: printing, storing, sending, updating. It is the parameter type of Iterable.forEach, Optional.ifPresent, Stream.forEach and Stream.peek. andThen chains consumers so that each value passes through several sinks in order.

Consumers chained with andThen
Figure 6 — Consumers chained with andThen

Supplier

Supplier<T> has T get() and produces values on demand. Its main use is laziness: deferring expensive work until it is needed and only if needed — Optional.orElseGet, Map.computeIfAbsent-style lazy initialisation, logging APIs that take message suppliers, Objects.requireNonNull(obj, () -> msg), ThreadLocal.withInitial, Stream.generate, and factories such as Collectors.toCollection(TreeSet::new).

A Supplier defers work until it is actually needed
Figure 7 — A Supplier defers work until it is actually needed

4How It Works Internally

The interfaces are plain Java interfaces annotated with @FunctionalInterface. Their combinators are default methods that return new lambdas — and is essentially t -> test(t) && other.test(t) — so a long chain creates a small chain of objects, each delegating to the next. The JIT usually inlines such chains at monomorphic call sites. Nothing is special-cased in the JVM.

JAVACombinators are default methods returning lambdas
// From java.util.function.Predicate (simplified)
@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    default Predicate<T> negate() { return (t) -> !test(t); }
    static <T> Predicate<T> not(Predicate<? super T> target) {
        return (Predicate<T>) target.negate();
    }
}

5APIs / Features / Syntax

InterfaceMethodCombinators / factoriesTypical JDK uses
Predicate<T>boolean test(T)and, or, negate, not, isEqualfilter, removeIf, anyMatch, Optional.filter
Function<T,R>R apply(T)andThen, compose, identitymap, computeIfAbsent, comparing, groupingBy
Consumer<T>void accept(T)andThenforEach, ifPresent, peek
Supplier<T>T get()—orElseGet, generate, withInitial, toCollection
The core interfaces across the JDK
Figure 8 — The core interfaces across the JDK

6Practical Examples

Example 1 — Composable business rules

JAVAPredicate composition
Predicate<Order> paid      = Order::isPaid;
Predicate<Order> large     = o -> o.total().compareTo(new BigDecimal("1000")) > 0;
Predicate<Order> domestic  = o -> "IN".equals(o.country());

Predicate<Order> needsReview = large.and(domestic.negate()).or(o -> o.flagged());
List<Order> review = orders.stream().filter(needsReview).toList();

List<String> tags = raw.stream().filter(Predicate.not(String::isBlank)).toList();

Example 2 — Functions as a mapping pipeline

JAVAFunction composition and identity
Function<String, String> normalise = s -> s.strip().toLowerCase(Locale.ROOT);
Function<String, Email> toEmail = Email::of;
Function<String, Email> parseEmail = normalise.andThen(toEmail);

Map<String, Customer> byId = customers.stream()
    .collect(Collectors.toMap(Customer::id, Function.identity()));

Example 3 — Consumers and suppliers

JAVAConsumers for side effects, suppliers for laziness
Consumer<Order> audit   = auditLog::record;
Consumer<Order> metrics = o -> registry.counter("orders").increment();
orders.forEach(audit.andThen(metrics));

// Lazy default: only built when the Optional is empty
Config cfg = loadOverride().orElseGet(() -> Config.loadDefaults(path));

// Lazy logging (System.Logger / java.util.logging)
logger.log(Level.DEBUG, () -> "state: " + expensiveDump());

// Memoising supplier for one-time initialisation
static <T> Supplier<T> memoize(Supplier<T> s) {
    return new Supplier<>() {
        private volatile T value;
        public T get() {
            T v = value;
            if (v == null) {
                synchronized (this) {
                    v = value;
                    if (v == null) value = v = s.get();
                }
            }
            return v;
        }
    };
}

7Common Problems & Mistakes

MistakeConsequenceBetter approach
orElse(expensive()) instead of orElseGetWork always doneorElseGet(() -> expensive())
Consumers with hidden shared state in parallel streamsRaces, lost updatesCollect results instead
Confusing andThen with composeFunctions applied in wrong orderandThen = this first
Predicate<Integer> in hot numeric codeBoxing on every callIntPredicate (2.2)
Checked exceptions inside Function lambdasCompile errors, ugly wrappingHandle locally, or a custom interface (2.3)
Suppliers that return different objects on each call when a singleton is expectedDuplicate expensive objectsMemoise explicitly

8Performance & Production Considerations

  • Boxing: Function<Integer, Integer> boxes both ways; primitive specialisations avoid it on hot paths.
  • Suppliers make expensive work conditional — a real saving for logging, defaults and fallbacks.
  • Composed predicates and functions add a delegation per step; negligible except in very tight loops.
  • Lambdas passed to frameworks should be stateless and thread-safe; many frameworks call them concurrently.

9Architecture & Design Considerations

Accept standard functional interfaces in your own APIs where they fit: callers can then pass lambdas, method references and JDK combinators without adapters. Use PECS wildcards in parameters (Predicate<? super T>, Function<? super T, ? extends R>). Prefer a named domain interface (2.3) when the concept deserves a name, needs several methods, or must throw checked exceptions — PricingRule communicates more than BiFunction<Order, Customer, Money>.

10Interview Questions & Answers

Q1L1 · BasicConcept

What are the four core functional interfaces and their methods?

The four core shapes in java.util.function are Predicate<T> with boolean test(T), Function<T, R> with R apply(T), Consumer<T> with void accept(T), and Supplier<T> with T get(). Each has exactly one abstract method, so a lambda or method reference can implement it. The easy way to remember them is by what goes in and what comes out: a Predicate takes a value and answers yes or no, a Function takes a value and returns another, a Consumer takes a value and returns nothing, and a Supplier takes nothing and returns a value. Most of the other 39 interfaces in the package are two-argument or primitive variants of these four.

Q2L1 · BasicConcept

Which interface does Stream.filter take? Stream.map? forEach?

Stream.filter takes a Predicate<? super T>, because it needs a yes-or-no answer for each element. Stream.map takes a Function<? super T, ? extends R>, because it turns each element into a new value, possibly of a different type. Stream.forEach takes a Consumer<? super T>, because it does something with each element and produces nothing. The same mapping appears across the JDK: removeIf and Optional.filter take predicates, computeIfAbsent and Comparator.comparing take functions, and Iterable.forEach and Optional.ifPresent take consumers. Recognising the shape from the signature is how you know what kind of lambda an API expects, and whether a method reference such as String::isBlank or Order::total fits.

Q3L2 · IntermediateTricky

What is the difference between f.andThen(g) and f.compose(g)?

Both build a combined function; they differ only in order. f.andThen(g) applies f first and passes its result to g, so it reads left to right like a pipeline. f.compose(g) applies g first and then f, which matches the mathematical notation f(g(x)). So f.andThen(g) is the same function as g.compose(f). For example, with trim as s -> s.strip() and upper as String::toUpperCase, trim.andThen(upper) and upper.compose(trim) both give "ABC" for " abc ". In practice most teams use andThen almost exclusively because it reads in execution order; mixing the two in one chain is a common source of functions applied in the wrong sequence.

Q4L2 · IntermediateTricky

Why is orElseGet usually preferable to orElse?

Because orElse evaluates its argument eagerly. Java evaluates method arguments before the call, so optional.orElse(loadDefaults()) runs loadDefaults every time, even when the Optional already holds a value and the result is thrown away. orElseGet takes a Supplier and calls it only when the Optional is empty, so the expensive work happens only if needed. The difference matters when the fallback queries a database, calls a service, allocates heavily or has side effects such as logging or metrics. For constants or values that already exist, orElse is fine and slightly cheaper, since no lambda is created. The same lazy pattern applies to orElseThrow with an exception supplier.

Q5L3 · Senior EngineerCode

How do you combine predicates, and do the combinations short-circuit?

Use the default methods and, or and negate, plus the static Predicate.not added in Java 11, which is useful with method references, as in filter(Predicate.not(String::isBlank)). For example, large.and(domestic.negate()).or(Order::isFlagged) builds a compound rule from small, named, testable predicates. And yes, the combinations short-circuit exactly like && and ||: the default and is implemented as t -> test(t) && other.test(t), so if the first predicate returns false the second is never called, and or stops at the first true. That makes ordering a tool: put cheap or most selective checks first and expensive ones, such as a lookup, last.

Q6L3 · Senior EngineerDesign

Why do JDK methods take Function<? super T, ? extends R> rather than Function<T, R>?

Because of PECS: a Function consumes its input and produces its output. Taking Function<? super T, ? extends R> lets callers pass a function that accepts any supertype of T and returns any subtype of R. So a Function<Object, String> or Function<Order, PremiumOrder> can be used where the method only needs to map orders to some result, without writing adapter lambdas. With a plain Function<T, R>, generic invariance would reject those perfectly safe arguments, forcing callers to write wrapper lambdas or casts. Following the same convention in your own APIs keeps them as flexible as the JDK's and avoids confusing compile errors for callers.

Q7L3 · Senior EngineerTricky

Why are Consumers risky in parallel streams?

Because a Consumer exists only for its side effect, and in a parallel stream that side effect runs concurrently on several ForkJoinPool threads. If it adds to an ArrayList, increments a plain counter or updates a HashMap, you get lost updates, corrupted structures or an occasional ArrayIndexOutOfBoundsException, and the failures are intermittent, so tests often pass. forEach also gives no ordering guarantee in parallel. The fix is to express the result as a reduction, with collect, toList, groupingBy or sum, so the framework combines per-thread results safely. If a side effect is unavoidable, use a thread-safe target such as ConcurrentHashMap or LongAdder, and keep it idempotent and cheap.

Q8L3 · Senior EngineerCode

How would you implement a lazily initialised, thread-safe value with a Supplier?

Wrap the Supplier in a memoising supplier that calls it at most once. The classic version holds the value in a volatile field and uses double-checked locking: get returns the field if set, otherwise synchronises, checks again and only then calls the delegate. volatile is essential so other threads see a fully constructed object. For a static value, the holder-class idiom is simpler, because class initialisation is lazy and thread-safe. Java 25 also offers StableValue as a preview API, whose StableValue.supplier method does this and lets the JIT treat the value as a constant. One gotcha: if the supplier returns null, the naive version calls it again on every get.

Q9L4 · Technical ArchitectTrade-off

When would you define a domain interface instead of using BiFunction or Function?

When the behaviour is a real domain concept rather than an anonymous shape. PricingRule with Money price(Order, Customer) says far more in signatures, stack traces and documentation than BiFunction<Order, Customer, Money>. A named interface is also the right choice when you need more than two parameters, checked exceptions, several methods, or domain-specific default combinators such as PricingRule.andThenDiscount. The cost is interoperability: a JDK API expecting a Function will not accept a PricingRule directly, although a method reference such as rule::price adapts it. My rule is standard interfaces for generic plumbing inside a module, named interfaces for anything that appears in a public or cross-team API.

Q10L4 · Technical ArchitectDesign

How do functional interfaces affect API design for shared libraries?

They make a library's extension points easy to use, because callers can pass lambdas, method references and JDK combinators instead of implementing adapter classes. For a shared library that means accepting the standard interfaces where the shape fits, with PECS wildcards such as Predicate<? super T>, and defining a named interface where the concept deserves a name or must throw checked exceptions. The contract must also be explicit in the Javadoc: whether the callback may be invoked concurrently and on which thread or executor, how often, whether it may block, and what happens if it throws. Without those rules, callers write lambdas with hidden shared state and the library inherits their bugs.

Q11L5 · Solution ArchitectDesign

How can functional interfaces make a rules or policy engine configurable without code changes to the engine?

Model the building blocks as functions and keep the engine generic. Conditions become Predicate<Order>, transformations Function<Order, Order> and actions Consumer<Order>, each implemented once, unit-tested in isolation and registered by name in a registry. A policy is then data, for example a YAML or database entry such as "when large and not domestic then flagForReview", which the engine composes with and, or, negate and andThen at load time. Adding a policy changes configuration, not the engine, and adding a new primitive only adds a registered function. Keep a whitelist of named functions rather than evaluating arbitrary scripts, version the policies and log which rule fired for auditability.

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 11 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.