TExcelTAD
Home › Java › Java Lambda Expressions

Java Lambda Expressions

A lambda expression is a short block of code that you can pass around like a value. Instead of writing a whole class just to describe one action — how to compare two items, what to do with each element, when to filter — you write the action inline. Lambdas arrived in Java 8 and are the foundation of the Streams API.

Syntax

java
(parameters) -> expression
(parameters) -> { statements; }
Form Example
no parameters () -> System.out.println("hi")
one parameter (parentheses optional) x -> x * 2
several parameters (a, b) -> a + b
with explicit types (String s) -> s.length()
block body with return (a, b) -> { int s = a + b; return s * s; }

Lambdas and functional interfaces

A lambda always implements a functional interface — an interface with exactly one abstract method. The lambda's parameters and body become that method's implementation:

java · try it yourself
interface Calculator {
    int apply(int a, int b);
}

class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        Calculator power = (base, exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) result *= base;
            return result;
        };
        System.out.println(add.apply(7, 5));
        System.out.println(power.apply(2, 8));
    }
}
12
256

Built-in functional interfaces

You rarely need to declare your own interface: java.util.function provides the common shapes.

Interface Method Takes → returns Example
Function<T, R> apply T → R s -> s.length()
BiFunction<T, U, R> apply T, U → R (a, b) -> a * b
Predicate<T> test T → boolean n -> n > 0
Consumer<T> accept T → nothing s -> System.out.println(s)
Supplier<T> get nothing → T () -> new ArrayList<>()
UnaryOperator<T> apply T → T s -> s.trim()
java · try it yourself
import java.util.function.*;

class Main {
    public static void main(String[] args) {
        Function<String, Integer> length = s -> s.length();
        Predicate<Integer> isEven = n -> n % 2 == 0;
        Consumer<String> shout = s -> System.out.println(s.toUpperCase() + "!");
        Supplier<String> greeting = () -> "Hello";
        BinaryOperator<Integer> max = (a, b) -> a > b ? a : b;

        System.out.println(length.apply("lambda"));
        System.out.println(isEven.test(7));
        shout.accept("watch out");
        System.out.println(greeting.get());
        System.out.println(max.apply(3, 11));

        // functions can be combined
        Function<Integer, Integer> plusOne = x -> x + 1;
        Function<Integer, Integer> doubled = x -> x * 2;
        System.out.println(plusOne.andThen(doubled).apply(5));
        System.out.println(isEven.negate().test(7));
    }
}
6
false
WATCH OUT!
Hello
11
12
true

Lambdas with collections

The collection classes accept lambdas in many methods, which removes a lot of loop boilerplate:

java · try it yourself
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("maya", "Theo", "ines", "Ravi", "lu"));

        names.removeIf(n -> n.length() < 3);
        names.replaceAll(n -> Character.toUpperCase(n.charAt(0)) + n.substring(1));
        names.sort((a, b) -> b.compareTo(a));       // reverse alphabetical
        names.forEach(n -> System.out.println("- " + n));

        Map<String, Integer> visits = new TreeMap<>(Map.of("home", 10, "shop", 4));
        visits.computeIfPresent("shop", (page, count) -> count + 1);
        visits.forEach((page, count) -> System.out.println(page + ": " + count));
    }
}
- Theo
- Ravi
- Maya
- Ines
home: 10
shop: 5

Method references

When a lambda only calls an existing method, a method reference (::) says the same thing more concisely:

Kind Method reference Equivalent lambda
static method Integer::parseInt s -> Integer.parseInt(s)
instance method of a parameter String::toUpperCase s -> s.toUpperCase()
method of a specific object System.out::println x -> System.out.println(x)
constructor ArrayList::new () -> new ArrayList<>()
java · try it yourself
import java.util.List;
import java.util.function.Function;

class Main {
    public static void main(String[] args) {
        Function<String, Integer> parse = Integer::parseInt;
        System.out.println(parse.apply("41") + 1);

        List<String> words = List.of("stream", "lambda", "record");
        words.stream().map(String::toUpperCase).forEach(System.out::println);
    }
}
42
STREAM
LAMBDA
RECORD

Capturing variables

A lambda can use local variables from the surrounding method, but only if they are effectively final — never reassigned after initialisation:

java
int bonus = 10;
Function<Integer, Integer> addBonus = x -> x + bonus;   // OK
bonus = 20;   // error: local variables referenced from a lambda must be final or effectively final

Tip: Keep lambdas short. If a lambda grows beyond a few lines, move the logic into a named method and use a method reference — it's easier to read and test.

Test yourself

Which interface does a lambda n -> n > 10 naturally fit?

  1. Supplier<Integer>
  2. Consumer<Integer>
  3. Predicate<Integer>
  4. Runnable

What is a functional interface?

  1. Any interface
  2. An interface with exactly one abstract method
  3. An interface with only default methods
  4. A class with one method

Which method reference is equivalent to s -> s.length()?

  1. String::length
  2. s::length
  3. String.length()
  4. length::String