Command Palette

Search for a command to run...

Back to the lesson: Topic 10.2 — Functional Interfaces
Core Java · Example 2 of 4 Java 11+

Composing functions, predicates and consumers

String::isEmpty is a method reference, a shorter way to write s -> s.isEmpty() (Topic 10.3). Predicate.not arrived in Java 11.

A functional interface is an interface with exactly one abstract method, and it is the only kind of type a lambda can become. java.util.function provides the standard shapes (Supplier, Consumer, Function, Predicate and friends), plus primitive versions that avoid boxing.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Build a Function<String, String> called clean by composing String::trim and String::toLowerCase with andThen, then apply it to " HeLLo World " and print the result in square brackets.

02

Write a method static List<Integer> filter(int[] nums, IntPredicate rule) and use it with a predicate for "even and greater than 10" built from two IntPredicates and and. Use {4, 12, 15, 20, 7}.

03

Declare @FunctionalInterface interface TriFunction<A, B, C, R> { R apply(A a, B b, C c); } and use it to compute a price from quantity, unit price and a discount percentage: 3, 250.0, 10 should give 675.0.

Explain it without notes

01

What exactly qualifies an interface as a functional interface?

02

Name the four main families in java.util.function and their method names.

03

Why do primitive specialisations like IntPredicate exist?

04

How do you deal with checked exceptions inside lambdas?

Composing functions, predicates and consumers Java 11+
Sign in to run this example in your browser.

Expected output

plus2.andThen(times3).apply(5) = 21
plus2.compose(times3).apply(5) = 17
identity: same
long AND starts with a: [apple, avocado]
long OR starts with a:  [apple, ant, banana, avocado]
NOT long:               [ant, fig]
not(isEmpty):           [x, y]
print order-1
log: [order-1]