SEARCH BY

All

  • All
  • Java8
  • Spring

What is method references in java8? what is the use of double colons :: in java8?

Post a Comment
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.

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());
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox