Lambda expression in Java

A lambda expression in Java is a way to write shorter code for implementing interfaces that have a single abstract method (called functional interfaces). It was introduced in Java 8 to make code more concise and readable, especially when working with APIs like Streams or event listeners.


General Syntax:

(parameters) -> expression
(parameters) -> { statements; }
  • If there’s only one parameter, parentheses () are optional.
  • If there’s only one statement, braces {} and return are optional.

Example 1: Using Lambda with Runnable

Before Java 8:

public class LambdaExample {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello from Runnable (before Java 8)");
            }
        };
        new Thread(runnable).start();
    }
}

With Lambda:

public class LambdaExample {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println("Hello from Runnable (using Lambda)");
        new Thread(runnable).start();
    }
}

Example 2: Lambda with Comparator

Before Java 8:

import java.util.*;

public class LambdaComparatorExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Alice", "Bob");
        
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        });

        System.out.println(names);
    }
}

With Lambda:

import java.util.*;

public class LambdaComparatorExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Alice", "Bob");
        
        Collections.sort(names, (s1, s2) -> s1.compareTo(s2));

        System.out.println(names);
    }
}

Example 3: Lambda with forEach

import java.util.*;

public class LambdaForEachExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Alice", "Bob");
        
        // Using lambda in forEach
        names.forEach(name -> System.out.println(name));
    }
}

✅ Key Point: Lambda expressions work with functional interfaces (interfaces with exactly one abstract method, like Runnable, Comparator, Callable, Consumer, etc.).

Leave a Reply