We can call or invoke methods directly with class name with :: operator by using class name, this process called as method reference.
We can refer to method or variable or constructor in java with :: operator which spelled as double colon operator.
We can refer to method or variable or constructor in java with :: operator which spelled as double colon operator.
Method reference to static method
Following is the syntax
ClassName::staticMethodName
Method reference to instance method
Following is the syntax
ClassName::instanceMethodName
Now to understand the real use of :: operator we will see the following example , sorting of names of array by using Stream concept , here we will use compareTo() method which is an instance method of Steam class.
List<String> names= new ArrayList<String>(){{ add("arjun"); add("raju"); add("bindhu"); add("jai"); }}; // sorting names without using method reference :: List<String> sortedNames= names.stream(). sorted( (n1,n2) -> n1.compareTo(n2) ).collect(Collectors.toList()); // sorting elements with method reference :: List<String> sortedNamesList= names.stream(). sorted(String.compateTo).collect(Collectors.toList());
Post a Comment
Post a Comment