Java 8: Lambda expressions replace anonymous classes

A lambda is a concise way to implement a functional interface (a single abstract method).

Code
Runnable r = () -> System.out.println("running via lambda");
r.run();

Comparator<String> byLen = (a, b) -> Integer.compare(a.length(), b.length());
var names = new ArrayList<>(List.of("bb", "a", "ccc"));
names.sort(byLen);
System.out.println(names);
Output
running via lambda
[a, bb, ccc]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26