Java Lambda Expressions
100%

Java Lambda Expressions

A lambda expression is a short way to write an implementation of a functional interface. Lambda expressions were introduced in Java 8 and are commonly used with collections, event handling, and functional programming.

1. What Is a Lambda Expression?

A lambda expression allows you to provide the behavior of a method without writing a separate implementation class.

Syntax:

(parameters) -> expression

Example:

public class Main {
    public static void main(String[] args) {
        Runnable task = () -> System.out.println("Hello Java");

        task.run();
    }
}
Output:
Hello Java

The () represents the parameters, -> is the lambda operator, and the statement after it is the task to execute.

2. Lambda Expression with One Parameter

If a lambda expression has one parameter, parentheses around the parameter can be omitted when its type is inferred.

interface Greeting {
    void sayHello(String name);
}

public class Main {
    public static void main(String[] args) {
        Greeting g = name ->
            System.out.println("Hello " + name);

        g.sayHello("Rahul");
    }
}
Output:
Hello Rahul

Here, name is the parameter passed to the lambda expression.

3. Lambda Expression with Multiple Parameters

A lambda expression can accept multiple parameters. Separate them with commas.

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

public class Main {
    public static void main(String[] args) {
        Calculator c = (a, b) -> a + b;

        System.out.println(c.add(10, 20));
    }
}
Output:
30

The lambda receives two numbers and returns their sum.

4. Lambda Expression with Multiple Statements

Use curly braces when a lambda expression contains multiple statements. If the lambda returns a value, use an appropriate return statement.

interface Calculator {
    int calculate(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        Calculator c = (a, b) -> {
            int result = a + b;
            return result;
        };

        System.out.println(c.calculate(15, 5));
    }
}
Output:
20
A lambda with a block body must return a value when implementing a method that requires a return value.
5. What Is a Functional Interface?

A functional interface is an interface with exactly one abstract method. It can be implemented using a lambda expression.

@FunctionalInterface
interface Message {
    void show();
}

public class Main {
    public static void main(String[] args) {
        Message m = () -> System.out.println("Welcome to Java");

        m.show();
    }
}
Output:
Welcome to Java

The @FunctionalInterface annotation asks the compiler to check that the interface follows the functional-interface rules.

6. Lambda Expression with forEach()

The forEach() method can use a lambda expression to perform an action for each item in a list.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List names = Arrays.asList(
            "Amit", "Rahul", "Priya"
        );

        names.forEach(name -> System.out.println(name));
    }
}
Output:
Amit
Rahul
Priya

The lambda executes once for each name in the list.

7. Using Lambda Expressions with Numbers

Lambda expressions can perform calculations through functional interfaces.

@FunctionalInterface
interface Square {
    int calculate(int number);
}

public class Main {
    public static void main(String[] args) {
        Square s = n -> n * n;

        System.out.println(s.calculate(5));
        System.out.println(s.calculate(8));
    }
}
Output:
25
64
8. Sorting a List Using Lambda

Lambda expressions can be used with sort() to define custom sorting behavior.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List numbers = new ArrayList<>(
            Arrays.asList(40, 10, 30, 20)
        );

        numbers.sort((a, b) -> a - b);

        System.out.println(numbers);
    }
}
Output:
[10, 20, 30, 40]

The lambda compares two numbers to define their order. For general-purpose sorting, prefer Integer.compare(a, b) instead of subtraction to avoid integer-overflow issues.

numbers.sort((a, b) -> Integer.compare(a, b));
9. Using Predicate with a Lambda

The Predicate functional interface represents a condition that returns true or false.

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate isEven = n -> n % 2 == 0;

        System.out.println(isEven.test(10));
        System.out.println(isEven.test(7));
    }
}
Output:
true
false

The test() method checks whether the supplied number satisfies the condition.

10. Using Function with a Lambda

The Function interface accepts one input and produces a result.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function getLength =
            text -> text.length();

        System.out.println(getLength.apply("Java"));
        System.out.println(getLength.apply("Programming"));
    }
}
Output:
4
11

The type parameters String and Integer represent the input and output types respectively.

11. Using Consumer with a Lambda

The Consumer interface accepts a value and performs an action without returning a result.

import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Consumer printMessage =
            message -> System.out.println(message);

        printMessage.accept("Learning Lambda Expressions");
    }
}
Output:
Learning Lambda Expressions

The accept() method executes the action defined by the lambda expression.

12. Lambda Expression vs Traditional Class
Lambda Expression Traditional Implementation
Usually requires less code. May require a separate class or anonymous class.
Uses the -> operator. Uses a method implementation.
Works with functional interfaces. Can implement interfaces using classes.
Useful for short behavior definitions. Useful for larger or reusable implementations.
Traditional Approach
interface Greeting {
    void sayHello();
}

class MyGreeting implements Greeting {
    public void sayHello() {
        System.out.println("Hello");
    }
}

public class Main {
    public static void main(String[] args) {
        Greeting g = new MyGreeting();
        g.sayHello();
    }
}
Lambda Approach
interface Greeting {
    void sayHello();
}

public class Main {
    public static void main(String[] args) {
        Greeting g = () -> System.out.println("Hello");
        g.sayHello();
    }
}
Output of Both Programs:
Hello
13. Java Lambda Assignments
  1. Create a lambda expression that prints "Hello Java".
  2. Create a functional interface that accepts a student's name and prints a greeting.
  3. Use a lambda expression to add two numbers.
  4. Write a lambda expression to calculate the square of a number.
  5. Use forEach() to print all elements of a list.
  6. Sort a list of integers in ascending order using a lambda expression.
  7. Use Predicate to check whether a number is positive.
  8. Use Function to convert a string to uppercase.
  9. Use Consumer to print each student's name.
  10. Create a lambda expression that checks whether a number is divisible by 5.

Quick Quiz: Java Lambda Expressions

Select the correct answer for each question.

1. Which operator is used in a lambda expression?



2. How many abstract methods can a functional interface have?



3. Which functional interface represents a condition returning true or false?