Stop 09 · Lambdas & StreamsTopics · 1/7

Lambda Expressions

Part of the Java Roadmap

In short

Before Java 8, passing a tiny piece of behaviour meant writing a five-line anonymous class. Lambdas let you write the same thing in one readable line, and every modern Java codebase is full of them.

Lambdas (Java 8+) are short anonymous functions like (a, b) -> a + b. They implement functional interfaces and replace most anonymous inner classes.

The jaadu tosses a long formal letter into a bin and slaps a small sticky note onto a fridge door instead.

Think of it like this

The sticky note instead of a letter

You want your flatmate to buy milk. You could write a formal letter with an address, greeting and signature (an anonymous class). Or you stick a note on the fridge: 'milk -> buy 2 packets'. A lambda is that sticky note: just the inputs, an arrow and what to do.

Watch it happen

Same sort, two ways

Anonymous class

  • new Comparator<String>() { ... }
  • Needs @Override and a full method signature
  • Five or six lines for one comparison
  • Creates a separate .class file

Lambda

  • (a, b) -> a.compareTo(b)
  • Parameter types are inferred
  • One line, easy to read
  • Works anywhere a functional interface is expected

Use a lambda whenever the target is a functional interface. Keep anonymous classes only when you need extra fields or several methods.

The big ideas

What you need to know

Shape: params -> body

x -> x * 2 for one parameter, (a, b) -> a + b for two, () -> 42 for none. Brackets are optional only with exactly one parameter.

Expression or block

A single expression returns its value automatically. With curly braces you write normal statements and need an explicit return.

Effectively final captures

A lambda can read local variables from the surrounding method, but only if they are never reassigned after being set.

Needs a target type

A lambda has no type of its own. It becomes a Comparator, Runnable or Predicate depending on where you pass it.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.Comparator;3import java.util.List;4 5public class LambdaDemo {6    public static void main(String[] args) {7        List<String> names = new ArrayList<>(List.of("Ravi", "Aisha", "Meera", "Kabir"));8 9        // Old way: anonymous inner class10        names.sort(new Comparator<String>() {11            @Override12            public int compare(String a, String b) {13                return a.compareTo(b);14            }15        });16 17        // Lambda: reverse order in one line18        names.sort((a, b) -> b.compareTo(a));19 20        names.forEach(name -> System.out.println("Hello, " + name));21 22        int minLength = 5;23        names.removeIf(name -> name.length() < minLength);24        System.out.println(names); // [Meera, Kabir, Aisha]25    }26}

1/4The pre-Java 8 way: a whole anonymous class just to compare two strings.

The same list sorted with an anonymous class and with a lambda, then printed and filtered with two more lambdas.

Save yourself the pain

Common mistakes

Oops

int count = 0; names.forEach(n -> count++);

Do this instead

This does not compile: captured locals must be effectively final. Use names.size(), a stream count(), or a normal for loop.

Oops

(a, b) -> { a + b; }

Do this instead

With braces you need a return: (a, b) -> { return a + b; }, or drop the braces: (a, b) -> a + b.

Oops

Writing a 20-line lambda with nested ifs.

Do this instead

Move long logic into a named private method and pass it with a method reference. Lambdas should stay short.

Your mission

Replace the anonymous classes

~20 min

Quick check

Which lambda correctly returns the larger of two ints?

Go deeper

  1. 1Rewrite an anonymous Comparator class as a lambda.
  2. 2Use list.forEach() and list.removeIf() with lambdas.
  3. 3Learn that lambdas can only use local variables that are effectively final.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge