• Lambda expressions are a concise way of representing anonymous functions in Java 8 and later. A lambda is an anonymous function
  • They can be used to pass behavior as a method argument, or to construct instances of functional interfaces.

Here’s a simple example of using a lambda expression to represent a function that takes two integers and returns their sum:


interface IntegerBinaryOperator {
    int apply(int a, int b);
}

class Main {
    public static void main(String[] args) {
        // Using a lambda expression to create an instance of IntegerBinaryOperator
        IntegerBinaryOperator adder = (a, b) -> a + b;
        
        // Using the lambda expression to perform the addition
        int result = adder.apply(3, 4);
        System.out.println(result); // Prints 7
    }
}

In this example, the IntegerBinaryOperator interface defines a single abstract method apply that takes two integers and returns an integer. The lambda expression (a, b) -> a + b provides an implementation for this method. This lambda expression can be assigned to a variable of type IntegerBinaryOperator, and can be used just like any other instance of this interface.

Here are a few real-world examples of using lambda expressions in Java 8:

  1. Sorting a list of objects:
List<Person> people = Arrays.asList(new Person("John", 30), new Person("Jane", 25), new Person("Jim", 35));

people.sort((p1, p2) -> p1.getAge() - p2.getAge());

System.out.println(people);
// Output: [Person{name='Jane', age=25}, Person{name='John', age=30}, Person{name='Jim', age=35}]
  1. Filtering a list of objects based on a condition:
List<Person> people = Arrays.asList(new Person("John", 30), new Person("Jane", 25), new Person("Jim", 35));

List<Person> youngPeople = people.stream().filter(p -> p.getAge() < 30).collect(Collectors.toList());

System.out.println(youngPeople);
// Output: [Person{name='Jane', age=25}]
  1. Performing an operation on each element of a list:
List<Person> people = Arrays.asList(new Person("John", 30), new Person("Jane", 25), new Person("Jim", 35));

people.forEach(p -> System.out.println(p.getName()));
// Output: 
// John
// Jane
// Jim

These are just a few examples of the many ways in which lambda expressions can be used to simplify code and improve readability in Java 8 and later.