
Java Lambda in Java
Lambda Expressions in Java
A lambda expression in Java is a concise way to represent an anonymous function (i.e., a function without a name) that can be passed around as a method argument or used to define the behavior of a method. Lambda expressions were introduced in Java 8 to enable functional programming capabilities and provide a more readable and flexible way to handle instances of functional interfaces.
Lambda expressions provide a clear and expressive syntax for writing code that can be passed as behavior (such as passing functions as arguments to methods).
Syntax of Lambda Expressions:
The syntax of a lambda expression consists of:
(parameters) -> expression or block of code
parameters
: A list of input parameters for the function.->
: The arrow token that separates the parameters from the body of the lambda.expression or block of code
: The body of the lambda expression, either a single expression or a block of code.
Basic Syntax Examples:
Single Parameter, Single Expression (no curly braces):
(x) -> x * x
Multiple Parameters, Single Expression (no curly braces):
(x, y) -> x + y
Multiple Parameters, Block of Code (with curly braces):
(x, y) -> { int sum = x + y; return sum;}
Functional Interfaces
A functional interface is an interface that has exactly one abstract method. Lambda expressions can only be used with functional interfaces. Some common examples of functional interfaces in Java are found in the java.util.function
package, such as Runnable
, Comparator
, Predicate
, Function
, etc.
For example:
@FunctionalInterfacepublic interface MyFunctionalInterface { void myMethod();}
Examples of Lambda Expressions in Java
1. Using Lambda with a Runnable
Interface:
public class LambdaExample { public static void main(String[] args) { // Using a lambda expression to implement Runnable interface Runnable runnable = () -> System.out.println("Hello from the thread!"); // Start a new thread using the lambda expression Thread thread = new Thread(runnable); thread.start(); }}
In this example, the Runnable
interface is implemented using a lambda expression. The lambda expression runs when the thread is started.
2. Lambda Expression with Comparator
Interface:
import java.util.*;public class LambdaComparatorExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry", "date"); // Sorting the list using lambda expression with Comparator Collections.sort(list, (s1, s2) -> s1.compareTo(s2)); // Print sorted list System.out.println(list); }}
In this example, the lambda expression (s1, s2) -> s1.compareTo(s2)
is used to provide a custom comparator for sorting the list of strings.
3. Lambda Expression with Predicate
Interface:
import java.util.*;public class LambdaPredicateExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry", "date"); // Using lambda expression with Predicate to filter strings that start with 'b' list.stream() .filter(s -> s.startsWith("b")) .forEach(System.out::println); }}
In this example, a lambda expression s -> s.startsWith("b")
is used to filter the list of strings, returning only those that start with the letter "b".
4. Using Lambda with Consumer
Interface:
import java.util.*;public class LambdaConsumerExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry", "date"); // Using a lambda expression with Consumer to print each string list.forEach(s -> System.out.println(s)); }}
Here, the forEach
method takes a Consumer
functional interface, and the lambda expression s -> System.out.println(s)
prints each element of the list.
Advantages of Lambda Expressions:
Conciseness: Lambda expressions eliminate the need for boilerplate code (like anonymous class definitions), making the code more concise and readable.
Readability: For simple operations (like filtering, transforming, etc.), lambda expressions make the code more expressive and easier to understand.
Flexibility: Lambda expressions can be passed as arguments to methods, allowing more flexible ways to handle behaviors in methods (like filtering or transforming collections).
Parallel Processing: Using lambda expressions with the Streams API enables easy parallel processing, improving performance in certain scenarios.
Lambda with Streams Example:
Lambda expressions are often used with the Streams API to perform various operations on collections. Here's an example of how to use a lambda expression to filter, transform, and collect elements from a list:
import java.util.*;import java.util.stream.*;public class LambdaStreamExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry", "date", "avocado"); // Using Streams with lambda to filter and collect strings that start with 'a' List<String> result = list.stream() .filter(s -> s.startsWith("a")) .map(String::toUpperCase) .collect(Collectors.toList()); // Print the result System.out.println(result); }}
Output:
[APPLE, AVOCADO]
In this example:
filter(s -> s.startsWith("a"))
filters the list to keep only strings starting with 'a'.map(String::toUpperCase)
transforms each string to uppercase.collect(Collectors.toList())
collects the results into a new list.
Summary of Lambda Expressions in Java:
Lambda Expression Syntax:
(parameters) -> expression or block of code
Functional Interfaces: Lambda expressions are used with interfaces that have a single abstract method.
Common Functional Interfaces:
Runnable
,Comparator
,Predicate
,Function
,Consumer
, etc.Benefits: Conciseness, readability, flexibility, and easier parallel processing.
Lambda expressions are a powerful feature in Java that simplifies the development of functional-style programs. If you have any specific questions or need further examples, feel free to ask! ?