Lambda expressions in Java provide a concise way to express behavior as a method argument, especially when working with collections. They were introduced in Java 8 to facilitate functional-style programming, enabling developers to write cleaner and more readable code.
Lambda expressions provide a concise way to represent anonymous functions — a function without a name — especially useful in functional programming with collections.
Lambda Expressions Syntax:
(parameters) -> { expression or statements }
Why Use Lambda Expressions with Collections?
In the Collections Framework, lambdas are mainly used for:
-
Iterating over elements
-
Filtering data
-
Transforming data
-
Sorting
-
Performing bulk operations
-
Working with Streams
Example 1: Iterating with forEach()
List<String> students = List.of("LotusJavaPrince", "Mahesh", "Datta");
students.forEach(name -> System.out.println("Hello " + name));
Code language: PHP (php)
forEach()
is a default method in Iterable
interface, which accepts a lambda to perform an action on each element.
Lambda expressions work beautifully with Java collections by making operations like filtering, iteration, transformation, and sorting more concise and expressive. This, when combined with Streams, brings modern, clean, and elegant code to Java.