Lambda Expressions in Java

Naveen AnamaneniUpdated · 5 min read

A lambda expression in Java is a short block of code that takes parameters and returns a value, written without a name. It is used to pass behavior as an argument to a method, for example "how to compare two students" or "what to do with each element". A lambda provides the implementation of a functional interface, an interface with exactly one abstract method. Lambdas were added in Java 8. In this lesson, you will learn the syntax of lambdas and see where they are used.

Syntax

Syntax
(parameters) -> expression
(parameters) -> { statements; }
  • Parameters: zero or more, in parentheses.
  • Arrow ->: separates the parameters from the body.
  • Body: a single expression (its value is returned automatically) or a block in braces (use return if a value is needed).

Forms of Lambda Expressions

FormExample
No parameters() -> System.out.println("Hi")
One parameter (parentheses optional)n -> n * n
Two parameters(a, b) -> a + b
With explicit types(String a, String b) -> a.length() - b.length()
With var (Java 11)(var a, var b) -> a + b
Block bodyn -> { int sq = n * n; return sq + 1; }

Example: Lambdas with Functional Interfaces

Let's see an example that stores lambdas in variables and calls them.

LambdaDemo.java▶ Try it
public class LambdaDemo {
    interface Greeter {
        String greet(String name);
    }
 
    interface Calculator {
        int apply(int a, int b);
    }
 
    public static void main(String[] args) {
        Greeter hello = name -> "Hello, " + name + "!";
        System.out.println(hello.greet("Navika"));
 
        Calculator add = (a, b) -> a + b;
        Calculator max = (a, b) -> {
            if (a > b) {
                return a;
            }
            return b;
        };
        System.out.println("3 + 4 = " + add.apply(3, 4));
        System.out.println("max(3, 4) = " + max.apply(3, 4));
 
        Runnable task = () -> System.out.println("Task running");
        task.run();
    }
}
Output
Hello, Navika!
3 + 4 = 7
max(3, 4) = 4
Task running

Explanation: Greeter and Calculator each have one abstract method, so a lambda can implement them. The lambda's parameters match the method's parameters, and its body becomes the method body. max uses a block body with return. Runnable is a built-in interface whose run method takes no parameters.

Example: Lambdas Passed to Methods

The most common use of a lambda is as an argument:

PassLambda.java▶ Try it
import java.util.ArrayList;
import java.util.List;
 
public class PassLambda {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(
            List.of("Srihitha", "Navika", "Advitha", "Anamaneni"));
 
        names.sort((a, b) -> a.length() - b.length());
        System.out.println("By length: " + names);
 
        names.removeIf(n -> n.startsWith("A"));
        System.out.println("Without A names: " + names);
 
        names.forEach(n -> System.out.println("Hi " + n));
    }
}
Output
By length: [Navika, Advitha, Srihitha, Anamaneni]
Without A names: [Navika, Srihitha]
Hi Navika
Hi Srihitha

Explanation: sort takes a lambda that compares two names, removeIf takes a lambda that tests a name, and forEach takes a lambda that acts on each name. Each method receives a small piece of behavior instead of a full class.

Common Mistakes

Using a lambda where the target isn't a functional interface. Object o = () -> {}; doesn't compile; a lambda needs a functional interface type.

Forgetting return in a block body that must return a value. (a, b) -> { a + b; } doesn't compile; write { return a + b; }.

Changing a local variable inside a lambda. Local variables used in a lambda must be effectively final (see "Effectively Final Variables and Lambda Capture").

Interview Corner

What is a lambda expression in Java?

A lambda expression is an anonymous function, written as (parameters) -> body, that provides the implementation of a functional interface's single abstract method. It lets you pass behavior as an argument, for example to sort, forEach or stream operations. Its parameter types are usually inferred from the target interface, and a single-expression body returns its value automatically.

Practice

  1. Easy: Write a functional interface Shape with a method double area(double side), and lambdas for a square's and a circle's area (using the side as the radius).
  2. Harder: Write a method applyTwice(Calculator c, int x) that returns c.apply(c.apply(x, x), x), and call it with three different lambdas.

Quick check: Lambda expressions

4 questions
1What does a lambda implement?
2Which lambda squares a number?
3When are parentheses around parameters optional?
4What does a single-expression body return?

Key Takeaways

Was this tutorial helpful?

Lesson 303 of 482