Pages

Java 8 Lambda Expression

Java 8 Lambda Expression

It is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code.They have no access modifier(private, public or protected), no return type declaration and no name.

Let us take a look at this example.
(int a, int b) -> {return a > b} .
This piece of code here is a lambda expression. Notice that the method has no access modifier, no return type declaration and no name.
Now, lets have a look at the example below:
interface Names {
  public void sayName(String name);
 
}
 
public class NameExample {
 
     public static void main(String[] args) {
        Names nameInstance = new Names() {
           @Override
           public void sayName(String name) {
               System.out.println("My Name is " + name);
          }
       };
      myName(nameInstance, "John");
    }
 
    private static void myName(Names nameInstance, String name) {
      nameInstance.sayName(name);
   }
}
This is what we will normally do without lambda expression and as you can see above, there is a lot of boilerplate code. It’s really tedious creating anonymous inner classes and implementing a whole lot of its methods. Now lets re-write the same code using lambda expression.
interface Names {
   public void sayName(String name);
 
}
 
public class NameExample {
 
     public static void main(String[] args) {
       myName(n -> System.out.println("My name is " + n), "John");
    }
 
     private static void myName(Names nameInstance, String name) {
      nameInstance.sayName(name);
    }
}
So as you can see here, lambda expression helps us write very simple code and also helped removed all those anonymous inner classes you would have had to create.
Syntax of Lambda
(args1, args2, args3, ……) -> { body }
Some facts of Lambda Expressions
  • It can have receive zero, one or more parameters. i.e ( ) -> { do something } ,(int a) -> { do something }, (int a, int b ,……,n) ->{do something }
  • Parameters must be enclosed in parenthesis and also must be separated with commas. ( int a, int b) -> { do something }
  • It is not mandatory to use parenthesis when there is a single parameter. a -> { do something}
  • When there is a single statement in its body, curly brackets are not mandatory.
    i.e ( ) -> return 45 can also be ( ) -> { return 45 };
Key Takeaways
  • Lambda expressions works nicely together only with functional interfaces. You cannot use lambda expressions with an interface with more than one abstract method.
  • To use lambda expressions, make sure you have Java 8 installed. Lambda expressions do not work on Java 7 and earlier versions.