Introduction to Java Lambda Expression
- 4 minutes read - 749 wordsAfter Java 8, developers can apply functional programming constructs in a pure Object-Oriented programming language through lambda expressions. Using lambda expression sequential and parallel execution can be achieved by passing behavior into methods. In Java world lambdas can be thought of as an anonymous method with a more compact syntax. Here compact means it is not mandatory to specify access modifiers, return type and parameter types while defining the expression.
There are various reasons for addition of lambda expression in Java platform but the most beneficial of them is we can easily distribute processing of collection over multiple threads. Prior to Java 8 if the processing of elements in a collection has to be done in parallel, client code was supposed to perform the necessary steps and not the collection. In Java 8 using Lambda Expression and Stream API we can pass processing logic of elements into methods provided by collections and now collection is responsible for parallel processing of elements not the client. Also parallel processing effectively utilizes multicore CPUs used now a days.
Lambda Expression
Syntax:
(parameters) -> expression
or
(parameters) -> { statements; }
Java 8 provide support for lambda expressions only with functional interfaces. FunctionalInterface
is also a new feature introduced in Java 8. Any Interface with single abstract method is called Functional Interface. Since there is only one abstract method, there is no confusion in applying the lambda expression to that method.
Benefits of Lambda Expression
- Less Lines of Code - One of the benefit of using lambda expression is reduced amount of code, see below example.
// Using Anonymous class
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Prior to Java 8");
}
};
// Runnable using lambda expression
Runnable r2 = () -> {
System.out.println("From Java 8");
};
- As we know in Java, lambda can be used only with functional interfaces. In above example Runnable is a functional interface, so we can easily apply lambda expression here.
- In this case we are not passing any parameter in lambda expression because the run() method of the functional interface (Runnable) takes no argument.
- Also syntax of the lambda expression says we can omit curly braces ({}) in case of single statement in the method body. In case of multiple statements, we should use curly braces as done in above example.
Sequential and Parallel Execution Support by passing behavior in methods
Prior to Java 8, processing elements of any collection can be done by obtaining an iterator from the collection and then iterating over the elements and then processing each element. If the requirement is to process the elements in parallel, it should be done by client code. With the introduction of Stream API in Java 8, functions can be passed to collection methods and now it’s responsibility of collection to process the elements either in sequential or parallel manner.
// Using for loop for iterating a list
public static void printUsingForLoop(){
List<String> stringList = new ArrayList<String>();
stringList.add("Hello");
for (String string : stringList) {
System.out.println("Content of List is: " + string);
}
}
// Using forEach and passing lambda expression for iteration
public static void printUsingForEach() {
List<String> stringList = new ArrayList<String>();
stringList.add("Hello");
stringList.stream().forEach((string) -> {
System.out.println("Content of List is: " + string);
});
}
Higher Efficiency (Utilizing Multicore CPU’s)
Using Stream API and lambda expression we can achieve higher efficiency (parallel execution) in case of bulk operations on collections. Also lambda expressions can help in achieving internal iteration of collections rather than external iteration as shown in above example. Now a days we have CPU’s with multicores, we can take the advantage of these multicore CPU’s by parallel processing of collections using lambda.
Lambda Expression and Objects
In Java any lambda expression is an object as they are instance of functional interface. We can assign a lambda expression to any variable and pass it like any other object. See below example how the lambda expression is assigned to a variable, and how it is invoked.
// Functional Interface
@FunctionalInterface
public interface TaskComparator {
public boolean compareTasks(int a1, int a2);
}
public class TaskComparatorImpl {
public static void main(String[] args) {
TaskComparator myTaskComparator = (int a1, int a2) -> {return a1 > a2;};
boolean result = myTaskComparator.compareTasks(5, 2);
System.out.println(result);
}
}
Where Lambda’s can be applied?
Lambda expressions can be used anywhere in Java where we have a target type. In Java we have target type in following contexts:
- Variable declarations and assignments
- Return statements
- Method or constructor arguments
Ref : https://www.javaworld.com/article/3452018/get-started-with-lambda-expressions.html
#lambda-expression #java 8 #java #whatsnew #introduction #tutorial #language #technology