Command Palette

Search for a command to run...

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

Your own functional interfaces, including one that throws

Inside the default method then, the lambda's apply(p) calls the enclosing PriceRule's own apply: this in a lambda is the enclosing object.

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?

Your own functional interfaces, including one that throws Java 8+
Sign in to run this example in your browser.

Expected output

1000 after rules = 850.0
parsed: [4, 8]
failed on -3: negative