Java 8 Lambda Expression Explained in 5 minutes

At IDR Solutions I spend alot of time on working on the development of our Java PDF Library. As I spend alot of time using Java 8 in our JavaFX PDF Viewer I thought that it might useful to to take a quick look at Java 8 and lambda expressions.

So what is 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.

Lets 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.

Hopefully you have found this quick guide useful. Next time I will be looking at ‘Java 8 streams Explained in 5 minutes‘.

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

Related Posts:

The following two tabs change content below.

Ernest Duodu

Developer at IDRSolutions
Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.
Ernest

About Ernest Duodu

Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

8 thoughts on “Java 8 Lambda Expression Explained in 5 minutes

  1. bancron

    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”);

    • Ernest Duodu

      Thanks for pointing out.

      • Stephen

        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

        • Stephen

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

        • 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. Keertiraj

    Nice Tutorial Ernest. Thanks for your effort and sharing your knowledge….

  3. Siavas Firoozbakht

    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!

  4. zhhk852

    has to say thanks for the great post

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>