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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Java
  4. Don't Fear the Lambda

Don't Fear the Lambda

If Java 8's lambda expressions made you nervous, here's a breakdown of their uses and examples of code refactoring to help you explain them.

Jayant Chaudhury user avatar by
Jayant Chaudhury
·
Nov. 10, 17 · Tutorial
Like (27)
Save
Tweet
Share
22.33K Views

Join the DZone community and get the full member experience.

Join For Free

I just want to share my experience in using lambda expressions in Java. I must say that I was always very skeptical how they could be used, where they could be used, and why they should be used. This fear stopped my understanding of this very interesting concept for a long time.

Lambda Expressions

To begin with, lambda expressions are actually functions written in Java used in our methods as a parameter objects. Earlier, we used to define functions in Java only in methods, but now we can use them inside method bodies.

Functional Interfaces

We can use a lambda expression wherever we have used a Functional Interface. Functional Interfaces are those interfaces in Java which have only one method to declare and be implemented, like the Runnable interface or Comparator interface.

Whenever we are changing code from the traditional way of coding to use lambdas, we should always followa few important steps.

Steps

Step 1: Remove the clutter code from Java by deleting all the declaration and type reference names. So, change something like this:

Collections.sort(pList, new Comparator<Person>() { 
    @Override public int compare(Person p1, Person p2) { 
        // TODO Auto-generated method stub 
        return p1.getName().compareTo(p2.getName()); 
    } 
});


To something like this:

Collections.sort(pList, (p1, p2) {
    return p1.getName().compareTo(p2.getName()); 
});


Step 2: Remove parentheses, add the lambda symbol, -> and remove the return:

Collections.sort(pList, (p1, p2) -> p1.getName().compareTo(p2.getName()); 


Lambda expressions are only concerned with the body of the function, NOT with the function name.

We can use lambda expressions wherever we have used anonymous functions, too.
We can use it in a new Thread class as well — here, we have used a lambda expression in place of Runnable interface code.

new Thread(() -> System.out.println("Run the thread"));   


Moreover, in Java 8, there were changes made to some interfaces to introduce methods to support lambda expressions. For example::

  • Collections.sort(lambda)

  • list.sort(lambda)

  • Iterable.forEach(lambda)

  • list.replaceAll(lambda)

  • Collections.removeIf(lambda)

These methods were created in Java 8 with the introduction of some other concepts.

Default Methods

Default methods were introduced to Interfaces in Java 8 where the default implementation is provided. Any class implementing an interface that does not provide the implementation uses a default method.

We can use a lambda expression in for-loop like:

for(Person s:pList){
    System.out.println(s.getName());
} 
// with lambdas, we can rewrite the code as below
list.forEach(p -> System.out.println(p.getName()); 


Using lambda expressions in for-loops will mean they are Internal Iterators, as there is one method call that will be uniform for all elements in the list.

Meanwhile, traditionally crafted for-loops have external iterators, as the elements in the for-loop are dependent on the outside object where it is declared, like looping a synchronized list that is declared outside the for-loop.

We can also rewrite the lambda expression in finer ways.

Higher Order Functions

Collections.sort(pList, (p1, p2) -> p1.getName().compareTo(p2.getName()); 
// can be rewritten as
pList.sort(Comparator.comparing(p -> p.getName()));


Method References Using Shortcut References

pList.sort(Comparator.comparing(Person :: getName));


Static Imports

We can also use static imports to rewrite the code as:

pList.sort(comparing(Person :: getName));


So if we compare the traditional code and with the code above, we can see how much boilerplate code has been removed.

I hope I was able to give a small insight of using lambda expressions hope any doubts are not there anymore. Below is a simple example to use the lambda expressions.

package com.corejava.practise;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


public class Person {
    int age;
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    String name;
    public Person(int age, String name) {
        super();
        this.age = age;
        this.name = name;
    }

    @Override public String toString() {
        return ("Person Name:" + this.getName() +
            " ::Person Age: " + this.getAge());
    }

    public static void main(String args[]) {
        Person[] personList = new Person[] {
            new Person(23, "Ravi"),
                new Person(23, "Anands"), new Person(32, "Suraj")
        };
        List < Person > pList = ((List) Arrays.asList(personList));
        System.out.println("UnSorted List is ::" + pList);
        // TODO SCENERIO 1: Remove the commented code to try using the customized Comparator Class
        // Collections.sort(pList, new PersonNameComparator() {
        // @Override
        // public int compare(Person p1, Person p2) {
        // // TODO Auto-generated method stub
        // return p1.getName().compareTo(p2.getName());
        // }
        // });

        // TODO SCENERIO 2:: Remove the commented code below to try using the Comparator Anonymous 
        //Inner class .. Functional Interface

        // Collections.sort(pList, new Comparator<Person>() {
        // @Override
        // public int compare(Person p1, Person p2) {
        // // TODO Auto-generated method stub
        // return p1.getName().compareTo(p2.getName());
        // }
        // });


        // TODO SCENERIO 3: Remove the commented code below to try using lambda expressions.. 
        //using default methods 
        //pList.sort((p1,p2) -> p1.getName().compareTo(p2.getName()));

        // TODO SCENERIO 4: Remove the commented code below to try using lambda expressions.. 
        //using higher order functions 
        //pList.sort(Comparator.comparing(p -> p.getName()));

        // TODO SCENERIO 5: Remove the commented code below to try using lambda expressions.. 
        //using method references 
        //pList.sort(Comparator.comparing(Person::getName));
        //System.out.println("\nsSorted List is ::" + pList);
    }
}


Interface (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner's Guide to Back-End Development
  • Exploring the Benefits of Cloud Computing: From IaaS, PaaS, SaaS to Google Cloud, AWS, and Microsoft
  • Best Practices for Writing Clean and Maintainable Code
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: