Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Don't Fear the Lambda

DZone's Guide to

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.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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


Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
lambda expression ,functional programing ,higher-order functions ,java ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}