Java method reference to a constructor example

This source code example demonstrates the usage of Java method reference to a constructor.

Well, a Java method reference to a constructor is a type of method reference introduced in Java 8.

Method reference is used to refer method of the functional interface. It is a compact and easy form of a lambda expression.

You can refer to a constructor by using the new keyword. In this example, we are referring constructor with the help of a functional interface. 

Syntax of method reference to a constructor

ClassName::new  

Java method reference to a constructor example 1

Let's create an example that converts List into Set using Lambda expression and then converts Lambda expression into method reference:
package com.java.lambda.methodref;

import java.util.*;
import java.util.function.Function;

public class MethodReferencesDemo {

    public static void main(String[] args) {

        // 4. reference to a constructor
        List<String> fruits = new ArrayList<>();
        fruits.add("Banana");
        fruits.add("apple");
        fruits.add("mango");
        fruits.add("watermelon");

        Function<List<String>, Set<String>> setFunction = (fruitsList) -> new HashSet<>(fruitsList);
        System.out.println(setFunction.apply(fruits));

        // using method reference
        Function<List<String>, Set<String>> setFunctionMethodRef = HashSet::new;
        System.out.println(setFunctionMethodRef.apply(fruits));
    }
}

Lambda expression:
        Function<List<String>, Set<String>> setFunction = (fruitsList) -> new HashSet<>(fruitsList);
        System.out.println(setFunction.apply(fruits));

Method reference:
        // using method reference
        Function<List<String>, Set<String>> setFunctionMethodRef = HashSet::new;
        System.out.println(setFunctionMethodRef.apply(fruits));
Output:

[apple, watermelon, Banana, mango]
[apple, watermelon, Banana, mango]

Java method reference to a constructor example 2

The below example demonstrates the usage of method reference to the constructor.
public class ReferenceToConstructor {
    public static void main(String[] args) {  
         Messageable hello = Message::new;  
         hello.getMessage("Hello");  
    }
}

interface Messageable{  
    Message getMessage(String msg);  
}  

class Message{  
    Message(String msg){  
        System.out.print(msg);  
    }  
}

Related Source Code Examples


Comments