Reference to a Constructor (Method References)
In this lesson, you will learn about the fourth and final kind of method reference, "a reference to a constructor".
Table of Contents
Reference to a Constructor
Constructor references are specialized forms of method references that refer to the constructors of a class. They can be created using the className
and the keyword new
.
Syntax
ClassName::new
Example
Let us write a simple example that contains four files.
Let's assume we have a class called Person
that takes a String
argument in its constructor to set the name of the person. We can create a method reference to this constructor using the following syntax:
Person::new
This creates a reference to the constructor of the Person
class that takes a String
argument. We can then use this constructor reference to create new Person
objects by passing the String
argument to the constructor reference.
For example, let's say we have a list of names and want to create a list of Person
objects with those names. We can use the map
method of the Stream
class along with the Person::new
constructor reference like this:
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ReferenceToConstructor {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Person> people =
names // collection of names stored in list
.stream() // stream of names
.map(Person::new) // calling the constructor
.collect(Collectors.toList());
System.out.println(people);
}
}
In this example, we use the map
method to apply the Person::new
constructor reference to each name in the names list. We pass the name as an argument to the constructor reference to create a new Person
object with that name. Finally, we collect the Person objects into a new list using the toList
or .collect(Collectors.toList())
method. The output of this program will be:
[Alice, Bob, Charlie]
👨🏻💻 Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.