Skip to lesson

Functional Interfaces, Lambdas and Method References

Lambdas and method references are behind every stream, Optional and Comparator question, so interviewers test them early. They check that you can name the core interfaces, explain what a lambda really is, and say why a captured variable must be effectively final.

The core interfaces: Function, Predicate, Consumer, Supplier, BiFunction

Function<T, R> is the functional interface for a calculation: R apply(T t) takes one value and returns one result. Predicate tests a value, Consumer uses a value, and Supplier gives one.

Learn the core interfaces by their shape: what goes in and what comes out. Each line below uses one of them on a college fee.

Example 1 · Each core interface in one line

CoreInterfacesDemo.javaJava
import java.util.function.BiFunction;import java.util.function.BinaryOperator;import java.util.function.Consumer;import java.util.function.Function;import java.util.function.Predicate;import java.util.function.Supplier;import java.util.function.UnaryOperator;
public class CoreInterfacesDemo {    public static void main(String[] args) {        Function<Integer, String> grade = m -> m >= 75 ? "Distinction" : "Pass";        Predicate<Integer> passed = m -> m >= 40;        Consumer<String> notify = msg -> System.out.println("SMS: " + msg);        Supplier<String> otp = () -> "482913";        BiFunction<Integer, Integer, Integer> total = (theory, lab) -> theory + lab;        UnaryOperator<String> shout = s -> s.toUpperCase();        BinaryOperator<Integer> max = (a, b) -> a >= b ? a : b;
        System.out.println("Function:       " + grade.apply(82));        System.out.println("Predicate:      " + passed.test(35));        notify.accept("Fees received");        System.out.println("Supplier:       " + otp.get());        System.out.println("BiFunction:     " + total.apply(62, 18));        System.out.println("UnaryOperator:  " + shout.apply("result out"));        System.out.println("BinaryOperator: " + max.apply(71, 88));
        Predicate<Integer> distinction = m -> m >= 75;        System.out.println("passed and not distinction (60): " + passed.and(distinction.negate()).test(60));        Function<Integer, Integer> addGrace = m -> m + 5;        System.out.println("addGrace then grade (72): " + addGrace.andThen(grade).apply(72));    }}
Output
Function:       Distinction
Predicate:      false
SMS: Fees received
Supplier:       482913
BiFunction:     80
UnaryOperator:  RESULT OUT
BinaryOperator: 88
passed and not distinction (60): true
addGrace then grade (72): Distinction

What this code does

  • Each variable's type says the shape: apply for Function and BiFunction, test for Predicate, accept for Consumer, get for Supplier.
  • The last two lines use default methods: passed.and(distinction.negate()) builds a new predicate, and addGrace.andThen(grade) runs addGrace first, then grade (72 + 5 = 77, a Distinction).

Model answer, spoken: "Function transforms, Predicate tests, Consumer consumes, Supplier supplies. They also have default methods to combine them: Predicate.and/or/negate, Function.andThen/compose, Consumer.andThen." Revise: java.util.function tour (opens in a new tab) and Composing functions (opens in a new tab).

Must know:

  • Function<T, R>: R apply(T t), one in, one out. Used by map.
  • Predicate<T>: boolean test(T t), a yes/no check. Used by filter. Consumer<T>: void accept(T t), takes and returns nothing. Used by forEach.
  • Supplier<T>: T get(), nothing in, one out. Used by orElseGet, generate. BiFunction<T, U, R>: two in, one out; BiConsumer, BiPredicate likewise.
  • UnaryOperator<T> is a Function<T, T>; BinaryOperator<T> is a BiFunction<T, T, T> (used by reduce). Primitive versions: IntPredicate, ToIntFunction, IntBinaryOperator and more.

Predict the output

Combine functions and predicates

Read each program and pick what it prints.

Round 1 of 4

f adds 2, g multiplies by 3. Run f first with andThen.

import java.util.function.Function;
public class FnA {
public static void main(String[] args) {
Function<Integer, Integer> f = x -> x + 2;
Function<Integer, Integer> g = x -> x * 3;
System.out.println(f.andThen(g).apply(4));
}
}

@FunctionalInterface rules

A functional interface is an interface with exactly one abstract method. Default methods, static methods and abstract methods that match public Object methods (such as equals) do not count.

Here is a custom FeeRule interface with a default and a static method. It still has one abstract method, so a lambda can implement it.

Example 2 · Your own @FunctionalInterface with default and static methods

CustomFunctionalDemo.javaJava
@FunctionalInterfaceinterface FeeRule {    int apply(int baseFee);                    // the single abstract method
    default FeeRule then(FeeRule next) {      // default methods are allowed        return fee -> next.apply(apply(fee));    }
    static FeeRule none() {                    // static methods are allowed        return fee -> fee;    }
    String toString();}
public class CustomFunctionalDemo {    public static void main(String[] args) {        FeeRule hostelDiscount = fee -> fee - 5000;        FeeRule lateFine = fee -> fee + 500;
        System.out.println(hostelDiscount.apply(90000));        System.out.println(hostelDiscount.then(lateFine).apply(90000));        System.out.println(FeeRule.none().apply(90000));    }}
Output
85000
85500
90000

What this code does

  • FeeRule has one abstract method, apply. The default method then, the static method none and the toString() declaration (an Object method) do not break the rule.
  • hostelDiscount.then(lateFine) returns a new FeeRule that applies the discount and then the fine: 90000 - 5000 + 500 = 85500.

@FunctionalInterface is optional. It asks the compiler to check the rule, so adding a second abstract method later fails with Unexpected @FunctionalInterface annotation ... multiple non-overriding abstract methods found. Without the annotation the interface still works with lambdas as long as it has one abstract method. Revise: Custom functional interfaces (opens in a new tab).

Must know:

  • One abstract method; any number of default and static methods.
  • Comparator is functional even though it declares equals, because that matches a public Object method.
  • Runnable, Callable, Comparator, ActionListener are functional interfaces too.
  • An interface extending a functional interface stays functional only if it adds no new abstract method.
  • A lambda's type comes from its target: the same lambda can be a Predicate or your own interface.

Find the bug

Which line breaks the rule?

Each snippet should be a functional interface. Tap the wrong line, then check the fix.

A payment rule used with a lambda.

Round 1 of 3

Four kinds of method references

A method reference is a short form of a lambda that only calls one existing method or constructor, written with ::. It has four kinds: static, bound object, arbitrary object of a type, and constructor.

A method reference replaces a lambda that only calls one method. Each of the four kinds below is shown with the lambda it replaces.

RefCompileSnip.javaJava
import java.util.List;
public class RefCompileSnip {    public static void main(String[] args) {        List<String> names = List.of("ravi", "asha", "meena");        names.stream()                .map(String::toUpperCase)                .sorted()                .forEach(System.out::println);    }}
Output
ASHA
MEENA
RAVI

Example 3 · All four kinds of method references

MethodRefDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.BiFunction;import java.util.function.Function;import java.util.function.Supplier;
public class MethodRefDemo {    record Student(String name) {}
    public static void main(String[] args) {        Function<String, Integer> parse = Integer::parseInt;          // s -> Integer.parseInt(s)        System.out.println("static:      " + (parse.apply("42") + 8));
        String college = "IIT ";        Function<String, String> prefix = college::concat;            // s -> college.concat(s)        System.out.println("bound:       " + prefix.apply("Madras"));
        Function<String, String> upper = String::toUpperCase;         // s -> s.toUpperCase()        BiFunction<String, String, Boolean> same = String::equalsIgnoreCase;        System.out.println("unbound:     " + upper.apply("pune") + " " + same.apply("UPI", "upi"));
        Supplier<List<String>> newList = ArrayList::new;        Function<String, Student> makeStudent = Student::new;        List<String> list = newList.get();        list.add("first");        System.out.println("constructor: " + list + " " + makeStudent.apply("Asha"));
        List.of("x", "y").forEach(System.out::println);    }}
Output
static:      50
bound:       IIT Madras
unbound:     PUNE true
constructor: [first] Student[name=Asha]
x
y

What this code does

  • The comments show the lambda that each of the first three kinds replaces. In String::toUpperCase the object comes from the argument; in college::concat the object is fixed in advance.
  • String::equalsIgnoreCase fits a BiFunction because the first argument becomes the object and the second the parameter. Student::new picks the record constructor that takes one String.

Interviewers often ask you to name the four kinds with an example of each. Revise: Method reference basics (opens in a new tab) and unbound instance references (opens in a new tab).

The four kinds:

  • Static method: Integer::parseInt means s -> Integer.parseInt(s).
  • Instance method of a particular object: System.out::println, college::concat means s -> college.concat(s).
  • Instance method of an arbitrary object of a type: String::toUpperCase means s -> s.toUpperCase(); the first argument becomes the object.
  • Constructor: ArrayList::new means () -> new ArrayList<>(); Student::new means n -> new Student(n).

Fix the error

Fix the method reference

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Create a student with no name.

import java.util.function.Supplier;
public class RefFix1 {
record Student(String name) {}
public static void main(String[] args) {
Supplier<Student> make = Student::new;
System.out.println(make.get());
}
}

Error

RefFix1.java:7: error: incompatible types: invalid constructor reference
        Supplier<Student> make = Student::new;
                                 ^
    constructor Student in record Student cannot be applied to given types

Effectively final variables in lambdas

A local variable is effectively final if it is assigned once and never changed afterwards, even without the final keyword. A lambda may use only effectively final local variables from its method.

A lambda can read a local variable only if it is never changed. Run this to see what compiles, and the clean fix.

Example 4 · Effectively final: what compiles and the clean fix

EffectivelyFinalDemo.javaJava
import java.util.List;import java.util.concurrent.atomic.AtomicInteger;
public class EffectivelyFinalDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 35, 88, 41);        int passMark = 40;        marks.stream().filter(m -> m >= passMark).forEach(m -> System.out.print(m + " "));        System.out.println();
        // int count = 0;        // marks.forEach(m -> count++);          // compile error: count is changed
        AtomicInteger count = new AtomicInteger();        marks.forEach(m -> {            if (m >= passMark) {                count.incrementAndGet();            }        });        System.out.println("Passed (AtomicInteger): " + count.get());
        long better = marks.stream().filter(m -> m >= passMark).count();        System.out.println("Passed (count()): " + better);    }}
Output
72 88 41
Passed (AtomicInteger): 3
Passed (count()): 3

What this code does

  • passMark is never reassigned, so the lambda may use it without final. Uncommenting count++ gives the compile error local variables referenced from a lambda expression must be final or effectively final.
  • AtomicInteger works because the variable count always points to the same object; only its contents change. count() on the stream gives the same answer with no shared state at all.

The lambda gets a copy of the value and may run later or on another thread, so a changing variable would be confusing and unsafe. Fields and array elements can be changed (only the local variable itself is restricted), which is why int[] count = {0} or an AtomicInteger compile. The cleaner fix is usually a stream result such as count() or sum(). Revise: Effectively final in lambdas (opens in a new tab).

Fix the error

Fix the captured variable

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

Add up the marks.

import java.util.List;
public class SumFix {
public static void main(String[] args) {
List<Integer> marks = List.of(72, 35, 88);
int total = 0;
marks.forEach(m -> total += m);
System.out.println(total);
}
}

Error

SumFix.java:7: error: local variables referenced from a lambda expression must be final or effectively final
        marks.forEach(m -> total += m);
                           ^

Lambda vs anonymous class: this and scope

A lambda shares the scope of the enclosing method and its this is the enclosing object. An anonymous class has its own scope, and its this is the anonymous object itself.

Print this from a lambda and from an anonymous class. The output shows who this is in each.

Example 5 · Predict the output: this in a lambda vs an anonymous class

ThisScopeDemo.javaJava
public class ThisScopeDemo {    private final String name = "outer ThisScopeDemo";
    void run() {        Runnable anonymous = new Runnable() {            private final String name = "anonymous Runnable";
            @Override            public void run() {                System.out.println("anonymous class this.name = " + this.name);            }        };        Runnable lambda = () -> System.out.println("lambda this.name          = " + this.name);
        anonymous.run();        lambda.run();        System.out.println("anonymous is a separate class: " + anonymous.getClass().isAnonymousClass());    }
    public static void main(String[] args) {        new ThisScopeDemo().run();    }}
Output
anonymous class this.name = anonymous Runnable
lambda this.name          = outer ThisScopeDemo
anonymous is a separate class: true

What this code does

  • In the anonymous class, this is the Runnable object, so this.name finds its own field. In the lambda, this is the enclosing ThisScopeDemo object.
  • isAnonymousClass() is true for the anonymous object: it is a real class compiled to its own file, while a lambda is not an anonymous class.

Both may read only effectively final local variables. An anonymous class can implement an interface with many methods or extend a class; a lambda only fits a functional interface. Revise: Lambda or method reference (opens in a new tab).

Must know:

  • An anonymous class compiles to its own .class file (Outer$1.class); a lambda is created at runtime.
  • An anonymous class can have fields and state; a lambda cannot.
  • In a lambda, declaring a variable with the name of an existing local is a compile error; in an anonymous class it shadows the outer one.

Next step

Check your understanding

12 quick questions