Search⌘ K
AI Features

Lambda Expressions

Explore how to use lambda expressions in Java to reduce boilerplate code and pass behavior efficiently. Understand syntax rules, type inference, and the concept of functional interfaces to improve your functional programming skills in Java.

Java allows us to pass behavior, such as a sorting rule or a task for a thread, through interfaces. Before lambda expressions, doing this required verbose anonymous classes, even for very small pieces of logic.

Lambda expressions reduce this overhead by letting us supply behavior directly while preserving Java’s type safety. This lesson explains how to write lambdas, how the compiler interprets them, and the syntax rules that keep code readable.

The boilerplate of anonymous classes

Before lambdas arrived, passing a block of code to a method required an anonymous inner class. This approach worked, but it was noisy. We had to declare a class, instantiate it, and override a method, even if we only needed a single line of logic.

Let’s look at how we traditionally sorted a list of strings by their length. We had to create a Comparator object and override its compare method.

Java 25
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class OldStyleSort {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Old way: Anonymous Inner Class
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return Integer.compare(s1.length(), s2.length());
}
});
System.out.println(names);
}
}
  • Line 14: We instantiate an anonymous implementation of Comparator.

  • Line 16: We explicitly write the method signature for compare, repeating the ...