Site iconJava PDF Blog

Java 8 Lambda Expression Explained in 5 minutes

At IDR Solutions I work on the development of our Java Developer libraries (a Java PDF Viewer and SDKPDF to HTML5 converter and a Java ImageIO replacement).

We are now updating them to Java8, and lambda expressions are one of the new features we are most excited about.

So what is a 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, let’s 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, let’s re-write the same code using a 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
Key Takeaways

If you found this article useful, you may also be interested in our other Java8 posts on Consumer suppliers, Streams API, Default MethodsMethod References, Optional and Repeating Annotations.

We also now have a large collection of articles on what is new in other versions of Java, including Java9.