Java 8 Method references in detail

 279 total views,  1 views today

In this tutorial let us learn about Java 8 method references in detail with a few examples.

Overview

Lambda expression was introduced in Java 8 to let you write simple and more concise code. It let you create anonymous methods. Kudos to Lambda expression to make developer life easier.

BUT …

There will be a scenario where lambda expression will just make a method call like below,

list.forEach(i -> System.out.println(i));

Can we still simplify this code?. The answer is yes by using Method references.

list.forEach(System.out::println);

A BIG THANKS to Java 8 method references.It made even more simpler.Method reference has replaced the lambda expression.

Method reference

  • Method reference is an excellent feature of Java 8 to write simple, clear, readable and reusable code.
  • Method reference can be a replacement for lambda functions, but not for all. They can only make a call to singular methods.
  • Method reference can be used to refer to a functional interface.

To put it simple,

Do you use an anonymous class, instead use lambda functions?
D
o you use lambda functions which just makes a call to a single method, instead use Method reference?

Double COLON operator

Usually we will make a call to a method using below syntax,

System.out.println("Hello World!")

If you notice, we are making a call to println method of System class.

This can be replaced by using Method reference ::(DOUBLE COLON operator)

System.out::println
Syntax: ClassName::methodname

There are four different kinds of method references.

1. Method Reference to a static method.

The following syntax can be used to simplify and shortened to code ClassName::staticMethodName.

Let us see an example,

public class Person
{

    private String name;
    private String age;
    private String city;
    private String gender;

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

    static boolean isMale(Person person)
    {
        if (person.getGender().equalsIgnoreCase("Male"))
        {
            return true;
        }
        return false;
    }

    //Getters and Setters
}

 public static void main(String[] args)
    {

        List<Person> persons = new ArrayList<>();
        persons.add(new Person("Raj", "22", "Chennai", "Male"));
        persons.add(new Person("Sekar", "22", "Chennai", "Male"));
        persons.add(new Person("Nikki", "21", "Madurai", "Female"));

      //Normal way of method call
      boolean value = persons.stream().anyMatch(p -> Person.isMale(p));

      //static method reference
      boolean value = persons.stream().anyMatch(Person::isMale);
       
    }

The above code makes a call to a static method of Person class. To simplify the code we have used below static method reference.

boolean value = persons.stream().anyMatch(Person::isMale);

This looks more elegant and readable.

Let us see an example using Lambda

Usually, we will declare the lambda expression the functional interface as below.

public class Test
{

    public static void main(String[] args)
    {

        Flyable flyable = () -> System.out.println("I am flying");
        flyable.fly();
    }
}

interface Flyable
{
    void fly();
}

Consider we would like to refer to a method in our lambda expression. In this case, we refer the method as below.

public class Test
{

    public static void main(String[] args)
    {

        Flyable flyable = Test::flyLikeBird;
        flyable.fly();
    }

    public static void flyLikeBird()
    {
        System.out.println("I am flying....");
    }

}

interface Flyable
{
    void fly();
}

2. Method reference to a instance method

The following syntax can be used to shortened to code Classname::methodName.

Let us see an example

public static void main(String[] args)
    {

        List<Person> persons = new ArrayList<>();
        persons.add(new Person("Raj", "22", "Chennai", "Male"));
        persons.add(new Person("Sekar", "22", "Chennai", "Male"));
        persons.add(new Person("Nikki", "21", "Madurai", "Female"));

        Person person = new Person();
        boolean value = persons.stream().anyMatch(eachPerson -> person.isEligible(eachPerson));

        System.out.println(value);
    }

The above code makes a call to a person instance method isEligible. This can be modified by using only the reference.

boolean value = persons.stream().anyMatch(person::isEligible);

Let us see an example using Lambda

public class Test
{

    public static void main(String[] args)
    {
        Test test = new Test();
        Flyable flyable = test::flyLikeBird;
        flyable.fly();
    }

    public void flyLikeBird()
    {
        System.out.println("I am flying....");
    }

}

interface Flyable
{
    void fly();
}

3. Method reference to a constructor

The following syntax can be used to refer to a constructor ClassName::new.

Let us see an example

public class Test
{
    public Test() {
        System.out.println("I am in contructor");
    }
    
    public Test(String arg) {
        System.out.println("I am in contructor with args "+arg);
    }

    public static void main(String[] args)
    {
        Flyable flyable = Test::new;
        flyable.fly();
        Talkable talkable = Test::new;
        talkable.talk("talk me..");
    }

}

interface Flyable
{
    void fly();
}

interface Talkable
{
    void talk(String arg);
}

Method reference could be applied to it using keyword new as a method name.

4. Reference to an Instance Method of an Object of a Particular Type

The following syntax can be used ObjectTypeName::methodName

long count = list.stream().filter(String::isEmpty).count();

Reference: Official documentation

Thanks for reading ๐Ÿ™‚ .Please provide your valuable comments.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.