What is the meaning of :: in the following code?
Set<String> set = people.stream() .map(Person::getName) .collect(Collectors.toCollection(TreeSet::new));
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory.
A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. In Java, a constructor is a block of codes similar to the method.
This is method reference. Added in Java 8.
TreeSet::new
refers to the default constructor of TreeSet
.
In general A::B
refers to method B
in class A
.
::
is called Method Reference. It is basically a reference to a single method. i.e. it refers to an existing method by name.
Method reference using ::
is a convenience operator.
Method reference is one of the features belonging to Java lambda expressions. Method reference can be expressed using the usual lambda expression syntax format using –>
In order to make it more simple ::
operator can be used.
Example:
public class MethodReferenceExample { void close() { System.out.println("Close."); } public static void main(String[] args) throws Exception { MethodReferenceExample referenceObj = new MethodReferenceExample(); try (AutoCloseable ac = referenceObj::close) { } } }
Set<String> set = people.stream() .map(Person::getName) .collect(Collectors.toCollection(TreeSet::new));
Is calling/creating a 'new' treeset.
A similar example of a Contstructor Reference is:
class Zoo { private List animalList; public Zoo(List animalList) { this.animalList = animalList; System.out.println("Zoo created."); } } interface ZooFactory { Zoo getZoo(List animals); } public class ConstructorReferenceExample { public static void main(String[] args) { //following commented line is lambda expression equivalent //ZooFactory zooFactory = (List animalList)-> {return new Zoo(animalList);}; ZooFactory zooFactory = Zoo::new; System.out.println("Ok"); Zoo zoo = zooFactory.getZoo(new ArrayList()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With