Lambda expressions were introduced in Java 8 as a way to provide functional programming features to Java. It allows developers to write more concise and readable code by representing a block of code as an expression.
A lambda expression consists of three parts: the parameters, the arrow operator, and the body. The parameters represent the inputs to the expression, the arrow operator separates the parameters from the body, and the body represents the actions to be taken with the input. Lambda expressions can be used wherever functional interfaces are used, which is any interface with a single abstract method.
Here is an example of a lambda expression that represents a block of code that takes in two integers and returns their sum:
// Defining a lambda expression that takes two integers
// and returns their sum
(int a, int b) -> a + b;
Lambda expressions can also be used with collections, allowing for more concise and readable code when performing operations on elements of a collection. Here is an example of using lambda expressions with the forEach method of a list:
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Using a lambda expression to print each name in the list
names.forEach(name -> System.out.println(name));
In this example, the lambda expression (name -> System.out.println(name)) is passed as an argument to the forEach method of the names list. This lambda expression takes a single parameter name and prints it to the console. The forEach method then applies this lambda expression to each element in the list, resulting in each name being printed to the console.
Lambda expressions provide a concise and powerful way to represent blocks of code and are widely used in modern Java programming.