Differences between Lambda Expression and Method Reference in Java?


Lambda expression is an anonymous method (method without a name) that has used to provide the inline implementation of a method defined by the functional interface while a method reference is similar to a lambda expression that refers a method without executing it. The arrow (->) operator can be used to connect the argument and functionality in a lambda expression while the (::) operator separates the method name from the name of an object or class in a method reference.

Syntax for Lambda Expression

([comma seperated argument-list]) -> {body}

Syntax for Method Reference

<classname> :: <methodname>

Example

import java.util.*;

public class LambdaMethodReferenceTest {
   public static void main(String args[]) {
      List<String> myList = Arrays.asList("INDIA", "AUSTRALIA", "ENGLAND", "NEWZEALAND", "SCOTLAND");
      System.out.println("------- Lambda Expression --------");

      // Using Lambda function to call system.out.println()
      myList.stream().map(s -> s.toUpperCase())
                     .forEach(s -> System.out.println(s));

      System.out.println("------- Method Reference ---------");

      // Using Method reference to call system.out.println()
      myList.stream().map(String :: toUpperCase).sorted()
                     .forEach(System.out :: println);
   }
}

Output

------- Lambda Expression --------
INDIA
AUSTRALIA
ENGLAND
NEWZEALAND
SCOTLAND
------- Method Reference --------
AUSTRALIA
ENGLAND
INDIA
NEWZEALAND
SCOTLAND
raja
Published on 18-Dec-2019 07:53:29
Advertisements