☕ Java

Lambda Expressions in Java 8

Java 8's lambdas let you pass behavior as data — write functions inline, without the ceremony of anonymous classes. They make your code dramatically shorter and more expressive, especially when working with collections.

What is a Lambda Expression?

A lambda expression is an anonymous function — a block of code you can pass around like a value. Before Java 8, passing behavior required creating a whole anonymous class. Lambdas cut that down to a single line. Syntax: (parameters) -> expression Or for multi-line logic: (parameters) -> { statements; return value; } Lambdas work with Functional Interfaces — interfaces with exactly ONE abstract method. The lambda provides the implementation for that method.

Lambdas vs. Anonymous Classes — The Transformation

Java
// BEFORE Java 8 — anonymous class. So much boilerplate.
Runnable r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Task running...");
    }
};

// WITH Java 8 lambdas — same thing in one line
Runnable r2 = () -> System.out.println("Task running...");

// With parameters
Comparator<Integer> ascOrder = (a, b) -> a - b;
Comparator<Integer> descOrder = (a, b) -> b - a;

// Multi-line lambda with braces
Comparator<String> byLength = (a, b) -> {
    if (a.length() != b.length())
        return a.length() - b.length();
    return a.compareTo(b);  // alphabetical if same length
};

Lambdas with Collections — Where They Shine

Java
import java.util.*;

List<String> names = Arrays.asList("Charlie", "Alice", "Bob", "David");

// Sort alphabetically — lambda replaces Comparator anonymous class
names.sort((a, b) -> a.compareTo(b));

// Even shorter with method reference
names.sort(String::compareTo);

// forEach — print each name
names.forEach(name -> System.out.println("Hello, " + name));

// Method reference — even shorter when the lambda just calls one method
names.forEach(System.out::println);

// Filter and collect — combined with Stream API
List<String> longNames = names.stream()
    .filter(name -> name.length() > 4)
    .collect(Collectors.toList());