Skills101

AdvancedJava Programming · Lesson 21 of 29 · Updated ·

Lambdas and Functional Interfaces in Java — In Depth, with Method References

The Java 8 lesson showed what a lambda is and how streams use them. This lesson goes deeper: how to read any lambda, which built-in interface to choose, how to combine small functions into bigger ones, and the four kinds of method references. These are exactly the points that output-prediction questions and interview follow-ups test.

1. A lambda is an object that implements one method

A functional interface is an interface with exactly one abstract method. A lambda is a short way to create an object of such an interface: you write only the method's parameters and body.

@FunctionalInterface
interface Discount {
    double apply(double price);
}

public class Main {
    public static void main(String[] args) {
        Discount festive = price -> price * 0.8;          // 20% off
        Discount flat = price -> Math.max(0, price - 150); // ₹150 off, never below 0
        double[] carts = {1000, 100};
        for (double c : carts) {
            System.out.println(c + " -> festive " + festive.apply(c) + ", flat " + flat.apply(c));
        }
    }
}
1000.0 -> festive 800.0, flat 850.0
100.0 -> festive 80.0, flat 0.0

@FunctionalInterface is optional, but it makes the compiler complain if someone adds a second abstract method later. Default and static methods do not count — Comparator has many of those and is still functional.

All the syntax forms

FormExample
no parameters() -> "hello"
one parameter (brackets optional)x -> x * x
several parameters(a, b) -> a + b
with types(int a, int b) -> a + b
block body (needs return)(a, b) -> { int s = a + b; return s * 2; }

An expression body returns its value automatically; a block body { … } needs an explicit return if the method returns something.

2. The java.util.function family

You rarely need to write your own interface. The package java.util.function has ready ones for the common shapes.

The main functional interfaces by shape: Supplier takes nothing and gives T; Consumer takes T and gives nothing; Predicate takes T and gives boolean; Function takes T and gives R; UnaryOperator takes T and gives T; BiFunction takes T and U and gives R; BinaryOperator takes two T and gives T

InterfaceMethodShapeTypical use
Supplier<T>get()() → Tcreate a default value lazily
Consumer<T>accept(t)T → nothingprint, save, send
Predicate<T>test(t)T → booleanfilter, check a rule
Function<T, R>apply(t)T → Rconvert, map
UnaryOperator<T>apply(t)T → Tchange a value of the same type
BiFunction<T, U, R>apply(t, u)(T, U) → Rcombine two values
BinaryOperator<T>apply(a, b)(T, T) → Tsum, max, merge (reduce)

For primitives there are versions without boxing: IntPredicate, IntUnaryOperator, IntBinaryOperator, ToIntFunction<T> and so on. Prefer them in number-heavy code.

import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        UnaryOperator<String> shout = s -> s.toUpperCase() + "!";
        BinaryOperator<Integer> bigger = (a, b) -> a >= b ? a : b;
        BiFunction<String, Integer, String> repeat = (s, n) -> s.repeat(n);
        IntPredicate isEven = n -> n % 2 == 0;           // no Integer boxing
        Supplier<double[]> emptyMarks = () -> new double[3];

        System.out.println(shout.apply("placed"));
        System.out.println(bigger.apply(72, 91));
        System.out.println(repeat.apply("ab", 3));
        System.out.println(isEven.test(10) + " " + emptyMarks.get().length);
    }
}
PLACED!
91
ababab
true 3

3. Combining functions

The built-in interfaces have default methods that join small functions into bigger ones — without writing new classes.

Function composition: f is x plus 2 and g is x times 10. f.andThen(g) runs f first then g, so 3 becomes 5 then 50. f.compose(g) runs g first then f, so 3 becomes 30 then 32

import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Function<Integer, Integer> addTwo = x -> x + 2;
        Function<Integer, Integer> timesTen = x -> x * 10;
        System.out.println(addTwo.andThen(timesTen).apply(3));   // (3 + 2) * 10
        System.out.println(addTwo.compose(timesTen).apply(3));   // 3 * 10 + 2

        Predicate<Integer> passed = m -> m >= 40;
        Predicate<Integer> distinction = m -> m >= 75;
        Predicate<Integer> passNoDistinction = passed.and(distinction.negate());
        for (int m : new int[]{35, 60, 88}) {
            System.out.print(m + ":" + passNoDistinction.test(m) + " ");
        }
        System.out.println();

        Consumer<String> log = s -> System.out.print("[log] " + s);
        Consumer<String> done = s -> System.out.println(" ... saved");
        log.andThen(done).accept("order 101");
    }
}
50
32
35:false 60:true 88:false 
[log] order 101 ... saved
  • f.andThen(g) = "do f, then g". f.compose(g) = "do g first, then f".
  • Predicate has and, or, negate, and the static Predicate.not(p).
  • Consumer.andThen runs two actions one after the other on the same value.

4. Method references: four kinds

When a lambda only calls one existing method, a method reference (::) says the same thing more briefly.

KindMethod referenceSame as the lambda
static methodInteger::parseInts -> Integer.parseInt(s)
method of a particular objectprefix::concats -> prefix.concat(s)
method of any object of a typeString::lengths -> s.length()
constructorStringBuilder::news -> new StringBuilder(s)
import java.util.*;
import java.util.function.*;

public class Main {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;          // static
        String prefix = "Roll-";
        Function<String, String> tag = prefix::concat;                 // particular object
        Function<String, Integer> len = String::length;                // any object
        BiFunction<String, String, Boolean> same = String::equalsIgnoreCase; // any object, 2 args
        Function<String, StringBuilder> make = StringBuilder::new;     // constructor

        System.out.println(parse.apply("41") + 1);
        System.out.println(tag.apply("007"));
        System.out.println(len.apply("Skills101"));
        System.out.println(same.apply("JAVA", "java"));
        System.out.println(make.apply("abc").reverse());

        List<String> names = new ArrayList<>(List.of("ravi", "asha", "om"));
        names.replaceAll(String::toUpperCase);
        names.forEach(System.out::println);
    }
}
42
Roll-007
9
true
cba
RAVI
ASHA
OM

The trickiest one is the third kind: in String::equalsIgnoreCase, the first argument becomes the object the method is called on, and the second becomes its parameter.

5. Capturing variables and returning lambdas

A lambda can use local variables from the surrounding method only if they are effectively final (never changed after being set). It can freely read and change fields. A method can also return a lambda, which lets you build functions from settings:

import java.util.function.*;

public class Main {
    static int callCount = 0;                       // a field: lambdas may change it

    static IntUnaryOperator multiplier(int factor) {
        return x -> {
            callCount++;
            return x * factor;                      // factor is captured
        };
    }

    public static void main(String[] args) {
        IntUnaryOperator twice = multiplier(2);
        IntUnaryOperator thrice = multiplier(3);
        System.out.println(twice.applyAsInt(21) + " " + thrice.applyAsInt(21));
        System.out.println("calls: " + callCount);

        int bonus = 5;
        // bonus++;                                  // would break the next line
        IntUnaryOperator addBonus = m -> m + bonus;
        System.out.println(addBonus.applyAsInt(70));
    }
}
42 63
calls: 2
75

Each call to multiplier returns a new function that remembers its own factor. Why must captured locals be effectively final? The lambda may run later, even on another thread, after the method has returned and its local variables are gone; Java copies the value, so it must not change.

Common mistakes

  • Writing a block body without return: x -> { x * 2; } does not compile.
  • Mixing up andThen and compose — read compose as "run the argument first".
  • Changing a local variable that a lambda uses (compile error "must be final or effectively final").
  • Using Function<Integer, Integer> in heavy number loops instead of IntUnaryOperator, causing boxing.
  • Long, multi-line lambdas: move the logic into a named method and use a method reference.

Quick recap

  • A lambda implements the single abstract method of a functional interface.
  • Built-ins: Supplier, Consumer, Predicate, Function, UnaryOperator, BiFunction, BinaryOperator, plus Int/Long/Double versions.
  • Combine: andThen, compose, and, or, negate.
  • Method references: static, particular object, any object of a type, constructor.
  • Captured local variables must be effectively final; lambdas can be returned from methods.

Practice what you learned

📝 Quiz: Lambdas and Functional Interfaces5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →