SrcForge

Lesson 34

Lambda Expressions

Lambda expressions are concise anonymous functions. Introduced in Java 8 for functional interfaces.

Java Track

Save progress as you learn.

61 lessons

Lesson content

Lambda expressions implement functional interfaces concisely. Introduced in Java 8.

Key Terms

  • Lambda Expression: Concise anonymous function implementation.
  • Functional Interface: Interface with exactly one abstract method.
  • Anonymous Function: Nameless function used inline.
  • Arrow Operator: -> separates parameters from body.

Syntax

(parameters) -> expression

// or

(parameters) -> {
    // code block
}

Example 1: No Parameters

interface Greeting {
    void sayHello();
}

public class LambdaExample {
    public static void main(String[] args) {
        Greeting greet = () -> System.out.println("Hello, World!");
        greet.sayHello();
    }
}

Output

Hello, World!

Example 2: With Parameters

interface Addition {
    int add(int a, int b);
}

public class LambdaAddition {
    public static void main(String[] args) {
        Addition sum = (a, b) -> a + b;
        System.out.println("Sum = " + sum.add(10, 20));
    }
}

Output

Sum = 30

Common Uses

// Sorting
list.sort((a, b) -> a.compareTo(b));

// Filtering
numbers.stream()
       .filter(n -> n > 10)
       .forEach(System.out::println);

// Iterating
names.forEach(name -> System.out.println(name));

FAQ

1. What is a lambda expression?

Concise anonymous function for functional interfaces.

2. When introduced?

Java 8.

3. Any interface?

No. Only functional interfaces with one abstract method.

Lambda expressions introduced in Java 8.
Only works with functional interfaces.
Arrow operator -> separates params from body.
Replaces verbose anonymous inner classes.
Works with streams, filters, collections.
Keep lambdas short and readable.
@FunctionalInterface enforces one abstract method.

Where Java is used

Java in real-world development

Lambda Syntax

(params) -> expression or (params) -> { block }

Functional Interface

One abstract method only. Use @FunctionalInterface annotation.

No Parameters

() -> System.out.println("Hello");

With Parameters

(a, b) -> a + b; Returns sum of two numbers.

Stream Use

filter(n -> n > 10).forEach(System.out::println)

Best Practice

Keep short. Use method references when possible.

Prev: GenericsBack to hub