What is Lambda Expression in Java: Simple Explanation and Example
lambda expression in Java is a short block of code that you can pass around and execute later, often used to simplify code that implements functional interfaces. It lets you write functions in a clear and concise way without needing a full class or method declaration.How It Works
Think of a lambda expression as a tiny, unnamed function you can write right where you need it. Instead of creating a whole new class or method, you write a quick piece of code that does a job, like a recipe you hand to someone to follow immediately.
In Java, lambda expressions work with functional interfaces, which are interfaces with just one abstract method. The lambda provides the code for that method. This makes your code shorter and easier to read, especially when working with collections or event handling.
Example
This example shows a lambda expression used to print each item in a list. It replaces the need for a full loop or anonymous class.
import java.util.List; import java.util.Arrays; public class LambdaExample { public static void main(String[] args) { List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry"); fruits.forEach(fruit -> System.out.println(fruit)); } }
When to Use
Use lambda expressions when you want to write simple, short pieces of code that can be passed around, like small tasks or actions. They are great for working with collections, such as filtering, sorting, or transforming data.
For example, when you want to respond to a button click in a user interface or process items in a list without writing bulky code, lambdas make your code cleaner and easier to understand.
Key Points
- Lambda expressions provide a clear and concise way to represent a single method interface implementation.
- They help reduce boilerplate code, especially with collections and event handling.
- They work only with functional interfaces (interfaces with one abstract method).
- Syntax includes parameters, arrow
->, and a body.