DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Trending

  • Introducing senro: A Pipeline Engine You Program in Go
  • Why Your AI Agent Works in the Demo and Fails in Production
  • Delta Lake UniForm to Snowflake: Cross-Platform Table Access Without a Second Copy
  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Lambda Expression in Java 8

Lambda Expression in Java 8

Java 8 Lambda expression

By 
Amit Datta
·
Sep. 03, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
11.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In my previous article I have explained all the functional interfaces introduced in java 8. Now I am going to explain some more details in lambda expression. The GitHub link for all the code examples used in this article is give at the end of this article. 

The plain and simple definition of Lambda expression – It is a function without having any name. It can be written exactly in place. It can even be used as a parameter in a function.

Initially, it sounds like vague or little confusing. Let’s look into some syntax followed by examples. 

(parameter to the function) -> {body of the function} 

In the above syntax function parameter is present, function body is also present but the function name is not present.

For example I would like to write one function called “addition” which will take two parameters and after adding those two parameters it will return the result. We can easily write this function without using lambda expression in the following way.

Java
 




x


 
1
static int addition(int a, int b)
2
{
3
  return a+b;
4
}



But we can declare the same using Lambda expression also. First I will show using the BiFunction functional interface and then I will show the same by creating a separate functional interface, respectively. 

Java
 




xxxxxxxxxx
1


 
1
static BiFunction<Integer,Integer,Integer> addition_Lambda = (a,b) -> {
2
  return a+b;
3
};



The following is the custom functional interface declared for this addition. 

Java
 




xxxxxxxxxx
1


 
1
static AdditionLambda<Integer,Integer,Integer> additionLambda = (a,b) -> {
2
  return a + b;
3
};



In the same way we can implement our different function using lambda expression. But it seems there is not much benefit rather making the simple things more complex. We will see how this lambda is beneficial for the java developer. 

Let’s take the Runnable interface which is being used to create new thread for asynchronous task. Before Lambda we have used the Runnable in our multiple applications to create new thread and assign a particular task to it. The code snippet is given below.

Java
 




xxxxxxxxxx
1
10
9


 
1
//Define Runnable prior to Java8
2
    static Runnable runnable = new Runnable() {
3
        @Override
4
        public void run() {
5
            System.out.println("Runnable Task");
6
        }
7
    };
8
//Invocation of Runnable prior to Java8
9
    new Thread(runnable).start();



But after Lambda expression has been introduced we can write the Runnable in the following way.

Java
 




xxxxxxxxxx
1


 
1
//Define Runnable using Runnable
2
    static Runnable runnableLambda = () -> {
3
        System.out.println("Runnable Task 1");
4
        System.out.println("Runnable Task 2");
5
    };
6
//Invocation of Runnable Lambda
7
    new Thread(runnableLambda).start();



Or, we can define the above in simpler way, given below.

Java
 




xxxxxxxxxx
1


 
1
//Define and invocation of Runnable using lambda in more precise way
2
new Thread(() -> {
3
  System.out.println("Runnable Task 1");
4
  System.out.println("Runnable Task 2");
5
}).start();



Similarly, we can show how the comparator interface can be implemented using lambda expression in more precise way.

The following code snippet is shown how comparator is being used without lambda expression.

Java
 




xxxxxxxxxx
1


 
1
static Comparator<Integer> comparator  = new Comparator<Integer>() {
2
        @Override
3
        public int compare(Integer intVar1, Integer intVar2) {
4
            return intVar1.compareTo(intVar2);
5
        }
6
    };
7
System.out.println(comparator.compare(6,4));



Then, find the below code snippet to show how comparator can be used using lambda expression.

Java
 




xxxxxxxxxx
1


 
1
static Comparator<Integer> comparatorByLambda = (a,b) -> a.compareTo(b);
2
System.out.println("Comparator Result using lambda: "+comparatorByLambda.compare(6,4));



Now, we can see how the lambda expression is beneficial for the java developers.

Now, I am going provide some of the example using lambda. These are very useful and java developers use these in frequent manner to build their java application.

  • How we can use the ArrayList using lambda
Java
 




xxxxxxxxxx
1
10
9


 
1
List<String> cities = Arrays.asList("Delhi", "Kolkata", "Chennai", "Mumbai");
2
System.out.println("Print name of cities without using lambda");
3
for(int i=0;i<cities.size();i++){
4
  System.out.println(cities.get(i));
5
}
6
System.out.println("Print name of cities using lambda");
7
cities.forEach((city)->{
8
  System.out.println(city);
9
});



  • How HashMap can be used using Lambda
Java
 




xxxxxxxxxx
1
11


 
1
Map<String,String> cityMap = new HashMap<>();
2

          
3
        cityMap.put("id","456329");
4
        cityMap.put("name","Tushar Sharma");
5
        cityMap.put("designation","Manager");
6

          
7
        cityMap.forEach((k,v)->{
8
            System.out.print("Key: "+k+"\t");
9
            System.out.print("Value: "+v+"\n");
10
 });



  • How lambda function can be passed as function parameter. Please find the below code example. In the below code the first argument of the function “getEmployeeName” is a argument of type functional interface and to pass the parameter value we have used lambda expression while invoking the function. 
Java
 




xxxxxxxxxx
1
11


 
1
public static String getEmployeeName(Function<Employee,String> getEmpInfoFn,Employee emp){
2
       return getEmpInfoFn.apply(emp);
3
    }
4
       System.out.println("How to use Lambda as function parameter. ");
5
       List<Employee> empList = EmployeeDB.getEmployees();
6
       Employee emp = EmployeeDB.getEmployees().get(0);
7
       String empName =  getEmployeeName(empVar->empVar.getName(),emp);
8
       String empDesignation = getEmployeeName(empVar->empVar.getDesignation(),emp);
9
       System.out.println("Employee Name: "+empName);
10
       System.out.println("Employee Designation: "+empDesignation);
10
       System.out.println("Employee Designation: "+empDesignation);



The supporting code examples used in the above article is given here. Please look into the package called lambda for the above code examples.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook