Lambda Expressions
Lambda expressions are a feature introduced in Java 8 to help you write cleaner, more concise code, especially when working with functions and collections. They allow you to express instances of single-method interfaces (functional interfaces) in a simpler and more readable way.
What is a Lambda Expression?
A lambda expression is a way to represent a method without a name, used mainly to simplify writing small pieces of code, especially for interfaces with a single method. Think of it as a shortcut for creating small functions that can be passed around and used in different places.
Why Use Lambda Expressions?
- Less Code: They make your code shorter and more readable.
- Functional Programming: Lambdas allow you to write functional-style code, making it easier to work with data in collections.
- Better Readability: They eliminate the need for boilerplate code, making code more expressive and focused on the task.
Syntax of a Lambda Expression
(parameters) -> expression // OR (parameters) -> { statements; }
- Parameters: The inputs to the function.
- Arrow (->): Separates the parameters from the body.
- Body: The code to execute.
Example:
Suppose we have a method that takes two numbers and adds them:
(int a, int b) -> a + b
Example of Using Lambda Expressions
Here's an example of using lambda expressions in Java. Let's say you have an interface that calculates something:
interface Calculator { int operate(int a, int b); }
Using a lambda, you can implement this interface without creating a new class:
Calculator add = (a, b) -> a + b; Calculator subtract = (a, b) -> a - b;
Now, you can use these lambdas to perform operations:
System.out.println("Addition: " + add.operate(5, 3)); // Output: 8 System.out.println("Subtraction: " + subtract.operate(5, 3)); // Output: 2
Working with Collections
Lambdas are especially useful when working with collections, such as lists. Here’s an example:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // Using lambda to filter names that start with "A" names.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println);
Key Benefits of Lambda Expressions
- Clean Code: Reduce boilerplate and improve readability.
- Enhanced Performance: Enable more efficient use of multi-core systems when used with Streams API.
- Flexibility with Functional Interfaces: Can be passed around as method parameters, enabling higher-order functions.
Common Functional Interfaces Used with Lambdas
Functional interfaces in Java have only one abstract method, making them perfect for lambdas. Here are some common ones:
- Predicate
: Takes a single input, returns true or false.
Predicate<String> isLong = str -> str.length() > 5;
- Consumer
: Takes a single input and returns nothing (used for operations like printing).
Consumer<String> printName = name -> System.out.println(name);
- Function
: Takes one input and returns one output.
Function<Integer, Integer> square = x -> x * x;
- Supplier
: Takes no input, but returns a value.
Supplier<Double> randomValue = () -> Math.random();