Lambdas, Functional Interfaces and Method References

Difficulty: Intermediate

Question

What is a lambda expression and a functional interface? Explain Predicate, Function, Supplier, Consumer, method references and the effectively final rule.

Answer

Java 8 changed how we write Java more than any release before or since, and lambdas are the heart of it. Let me explain what problem they solve and then the vocabulary that interviewers expect.

Before Java 8, if you wanted to pass behaviour, for example a sorting rule or a callback, you had to create an anonymous inner class, five lines of ceremony for one line of logic. A lambda expression is a short, anonymous function: (parameters) -> expression or { statements }. It lets you pass behaviour as if it were data.

A lambda needs a target type, and that type must be a functional interface: an interface with exactly one abstract method (SAM). Default and static methods do not count, and neither do methods that re-declare Object methods like equals. Runnable, Callable, Comparator and ActionListener are functional interfaces. The optional annotation @FunctionalInterface makes the compiler enforce the single-method rule, which protects you from accidentally adding a second abstract method later.

The java.util.function package provides ready-made ones, and you should know the core five. Predicate<T> takes a T and returns boolean (test), used for filtering; it has and, or and negate. Function<T,R> takes T and returns R (apply); it has andThen and compose. Consumer<T> takes T and returns nothing (accept), used for side effects like printing. Supplier<T> takes nothing and returns T (get), used for lazy creation. UnaryOperator<T> is a Function from T to T, and BinaryOperator<T> combines two Ts. There are also Bi-versions (BiFunction, BiPredicate, BiConsumer) and primitive specializations (IntPredicate, ToIntFunction, IntFunction) that avoid boxing.

Method references are shorthand for lambdas that simply call an existing method. There are four kinds: a static method (Integer::parseInt), an instance method of a particular object (System.out::println), an instance method of an arbitrary object of a type (String::toUpperCase, where the first argument becomes the receiver), and a constructor (ArrayList::new).

Now the rule about captured variables. A lambda can use local variables from its enclosing method only if they are final or effectively final, meaning never reassigned after initialization. The reason: local variables live on the stack of the enclosing method, but the lambda may run later or on another thread, so Java captures a copy of the value; allowing changes would create confusing inconsistencies. Instance and static fields, however, can be modified freely because they live on the heap. And unlike anonymous classes, inside a lambda the keyword this refers to the enclosing class instance, not the lambda itself, and a lambda does not introduce a new scope for variable names.

Under the hood, lambdas are not compiled to inner classes. The compiler generates a private synthetic method and uses invokedynamic with LambdaMetafactory to create the functional object at runtime, which is lighter than an anonymous class file per lambda.

Two practical cautions. Lambdas cannot throw checked exceptions unless the functional interface's method declares them, which is the most annoying part when working with I/O in streams; wrap in a helper or convert to unchecked exceptions. And keep lambdas short. If the body takes more than a few lines, extract it into a named method and use a method reference for readability and testability.

Code examples

Common functional interfaces

import java.util.*;
import java.util.function.*;

public class LambdaDemo {
    @FunctionalInterface
    interface Greeter {
        String greet(String name);
    }

    public static void main(String[] args) {
        Function<Integer, Integer> dbl = x -> x * 2;
        Function<Integer, Integer> inc = x -> x + 1;
        System.out.println(dbl.andThen(inc).apply(5));
        System.out.println(dbl.compose(inc).apply(5));

        Predicate<String> isEmpty = String::isEmpty;
        System.out.println(isEmpty.negate().test("hi"));

        Supplier<List<String>> maker = ArrayList::new;
        List<String> names = maker.get();
        Consumer<String> adder = names::add;
        adder.accept("Asha");
        System.out.println(names);

        int base = 10;
        BiFunction<Integer, Integer, Integer> f = (a, b) -> a * b + base;
        System.out.println(f.apply(3, 4));

        Greeter g = n -> "Hello, " + n;
        System.out.println(g.greet("InternHack"));
    }
}

andThen applies dbl first (5 becomes 10, then 11); compose applies inc first (6, then 12). The lambda captures base, which is effectively final. The custom Greeter shows a user-defined functional interface.

Key points

Common follow-up questions

Interview tips

Concepts covered

Lambda, Functional Interface, Method Reference, Predicate, Function

More Core Java & Collections questions