Ernest Duodu Ernest is a Java developer. Outside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

Are you a Java Developer working with PDF files?

Find out why you should be using JPedal

Java 8 Lambda Expression Explained in 5 minutes

1 min read

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
  • It can 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 work 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.

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.



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Ernest Duodu Ernest is a Java developer. Outside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

9 Replies to “Java 8 Lambda Expression Explained in 5 minutes”

  1. Hi,

    Thanks for the great posts. In your second example, it says

    myName(n -> System.out.println(“My name is ” + n), “John”);

    I think it should be

    myName(n -> System.out.println(“My name is ” + n), “John”);

      1. I thank you for some great, clearly explained content here Ernest.

        I wanted to point out (not a criticism, just an “fyi” if you’d not seen it) – the rendering issue for the expressions where “->” is rendered as “>” happens in the Consumer/Supplier post and perhaps a couple other places. A Transformer or parser output issue I might guess.

        Anyway – once I realized my slightly-rusty java knowledge was not missing some other new syntax – the newly introduced “>” operation – it was all good 😉

        Cheers,
        Stephen

        1. lol.. had my own rendering problem. it shows as just “>”… but I am typing -> i.e. minus-ampersand-gt-semicolon

        2. Hi Stephen,

          We’re glad you enjoyed the article. Thank you for pointing that out to us. I have changed it so that it should now display correctly.

          Thanks again,
          Sophia

  2. I haven’t had a clue about Lambda Expression before coming to this blog – using it will surely impress my tutor!

    Thank you for this easy-to-understand and useful post, Ernest!

  3. Clear and crisp explaination. Befor coming to this website, I read few others and got confused. But is to the point and explains beautifully. Thanks a lot for simplifying this.

Comments are closed.