search
top

Lambda Expressions with Java 8

ShareShare on FacebookShare on Google+Email this to someoneTweet about this on TwitterShare on LinkedIn

Before we discuss about the Lambda expressions, it is important to know what made Java introduce this to the world. Scala programming language has become very popular among Java developers since past few years. Scala design was aimed to address many challenges with Java language. Scala has many features and some of them are not present in Java like operator overloading, named parameters, optional parameters etc. Scala has very minimalistic syntax compared to Java. Scala helps you focus more on functional programming rather than juggling with lots of grammar.

Below is a good example to understand the difference by declaring a mathematical function.

 

// Java:

int mathFunction(intnum){

int numSquare=num*num;

return(int)(Math.cbrt(numSquare)+Math.log(numSquare));

}

 

// Scala: More idiomatic

// Uses type inference, omits `return` statement,

// uses `toInt` method, declares numSquare immutable 

import math._

def mathFunction(num:Int)={

val numSquare=num*num(cbrt(numSquare)+log(numSquare)).toInt

}

Courtesy: Wiki

There are couple of main syntax differences in the above code snippets. Scala code does not need the semicolons at the end of each statement. Also return keyword is not required for returning the result from the function (What else you expect from a last line inside a method ).

Java made an attempt to simplify some of the syntaxes by introducing the Lambda Expression in Java 8 version. Also this is an attempt to move towards Functional Programming.

 

What is Lambda Expression?

General meaning of Lambda Expression is anonymous function. A function which can be defined without using any class, and called without using any identifier.

 

How to use Lambda Expression?

Lambda Expressions in Java 8 is used when you want to define and call the function declared in an interface. Lambda Expressions are most effective to use method of a Functional Interface (Interface with single method declared). There are many functional interfaces present in Java library itself and one of them is Runnable interface.

 

Below is the code snippet uses Runnable interface without Lambda Expression.

public class RunnableExample {

       public static void main(String[] args) {

              Thread myThread = newThread(new Runnable()

                    @Override

                     public void run() {

                           System.out.println(“Thread is running.”);

                     }

              });

             myThread.start();

       }

}

 

And below code snippet achieves same result with Lambda Expression.

public class RunnableExample {

       public static void main(String[] args) {

              Runnable myThread = () -> {System.out.println(“Thread is running.”);};

              myThread.run();

       }

}

 

The difference is clear – instead of seven lines, it achieves result with only two line of codes (Though no compromise with semicolon). It removes a lot of boilerplate code and makes the code more readable. The message is clear – focus on what you want to achieve, don’t be boring. This makes sense, isn’t it?

So Java is still there, firmly holding its high grounds. Long live Java.

 

References and further readings:

http://www.codejava.net/java-core/the-java-language/java-8-lambda-runnable-example

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html

 

  • author's avatar

    By: Japan Trivedi

    Japan Trivedi is adventurous explorer of world of programming since last seven years. Apart from .Net and PHP, he has interest in web technologies based in Java/J2EE. Spring Framework has always been fascinating for him to work on. Problem solving and team work are one of the best qualities of him.

  • author's avatar

  • author's avatar

    See all this author’s posts

20 Responses to “Lambda Expressions with Java 8”

  1. Milestrush says:

    I like everything you post. You’ve done fantastic job.

  2. Waynesom says:

    This is a good article. This site is loaded with lots of interesting things.

  3. Edward Unomy says:

    Many thanks for helping people get the information they need. Good stuff as always. Keep up the great work!!!

  4. Steven Alent says:

    Thanks for sharing with us, I always learn new things from your posts.

  5. JosiahgEone says:

    Thank you for your fantastic blog. It was actually very helpful. I am so happy I found this.

  6. Lamontaftes says:

    Great post. I love it a lot. I was pretty lucky to discover your site. There’s a lot of helpful info!

  7. Jamesduh says:

    I enjoy all your posts. You’ve done really good job.

  8. GregoryJal says:

    It’s my very first time visiting your blog and I am very interested. Thank you for sharing and keep up 😉

  9. Thomas says:

    This is my very first time visiting your website and I am very fascinated. Thanks for sharing and keep up

  10. Johnsonwar says:

    Good post, I love it very much.I was pretty lucky to discover your website. There’s a lot of useful info!

  11. Jerrydow says:

    Great post. I enjoyed it so much. I was pretty lucky to discover your website.

  12. George werly says:

    Wow! This could be one of the most useful things on the matter I’ve ever found. Thanks for your effort.

  13. Matthews says:

    I love everything you post. You’ve done great job.

  14. Wiley says:

    Nice post. I learn something new and challenging on websites I stumble upon on a daily basis.

  15. Robert Stity says:

    Wonderful website, how do u get all this info? I’ve read through a few posts on your website and I like your style. Thanks a million, keep up the great work.

  16. Adidas says:

    I’m often to running a blog and i really appreciate your content. The article has really peaks my interest. I’m going to bookmark your website and preserve checking for brand new information.

  17. n_raj_2003 says:

    Lambda expressions address the bulkiness of anonymous inner classes by converting five lines of code into a single statement.

  18. Very well written story. It will be helpful to anyone who utilizes it, as well as myself. Keep doing what you are doing – for sure i will check out more posts.

  19. Netho says:

    It improves upon this approach with local and anonymous classes, and then finishes with an efficient and concise approach using lambda expressions.

Leave a Reply to Edward Unomy Cancel reply

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

top