Java- Lambdas

Lambdas

Lambda’s are used to provide the implementation of Functional interface, Less coding.

Lambda Expressions syntax is (argument) -> (body). Now let’s see how we can write above anonymous Runnable using lambda expression.

Runnable r1 = () -> System.out.println("My Runnable");
  • The body of a lambda expression can contain zero, one or more statements.

  • When there is a single statement curly brackets are Optional and the return type of the anonymous function is the same as that of the body expression.

  • When there are more than one statements, then these must be enclosed in curly brackets (a code block) and the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned

1.Zero parameter:

() -> System.out.println("Zero parameter lambda");

2.One parameter:–

(p) -> System.out.println("One parameter: " + p);

It is not mandatory to use parentheses, if the type of that variable can be inferred from the context

3.Multiple parameters -

(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);


Java Lambda Expression Example: ForEach Loop

Java provides a new method forEach() to iterate the elements. It is defined in Iterable and Stream interface. It is a default method defined in the Iterable interface. Collection classes which extends Iterable interface can use forEach loop to iterate elements.

default void forEach(Consumer<super T>action)

-performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”

public class LambdaExpressionExample7{  
    public static void main(String[] args) {            
        List<String> list=new ArrayList<String>();  
        list.add("ankit");  
        list.add("mayank");  
        list.add("irfan");  
        list.add("jai");            
        list.forEach(  
            (n)->System.out.println(n)  
        );  
    }  
}

This code will print every element of the list. You can even replace lambda expression with method reference because we are passing the lambda parameter as it is to the System.out.println() method as list.forEach(System.out::println);

If both Passing Paramter & Priniting parameter is same we can use System.out::println

  • forEach() is a terminal operation, which means once calling forEach() method on stream, you cannot call another method. It will result in a runtime exception.

  • When you call forEach() on parallel stream, the order of iteration** is not guaranteed**, but you can ensure that ordering by calling forEachOrdered() method.

  • There are two forEach() method in Java 8, one defined inside Iterable and other inside java.util.stream.Stream class. If purpose of forEach() is just iteration then you can directly call it e.g. list.forEach() or set.forEach() but if you want to perform some operations e.g. filter or map then better first get the stream and then perform that operation and finally call forEach() method.

  • Use of forEach() results in readable and cleaner code.


Java Lambda Expression Example: Comparator

Collections.sort(list,(p1,p2)->{  
    return p1.name.compareTo(p2.name);  
    });  
    for(Product p:list){  
        System.out.println(p.id+" "+p.name+" "+p.price); 
    }