This article is in continuation to my other posts on Functional Interfaces, static and default methods and Lambda expressions.
Method references are the special form of Lambda expression. When your lambda expression are doing nothing other than invoking existing behaviour (method), you can achieve same by referring it by name.
::
is used to refer to a method.- Method type arguments are infered by JRE at runtime from context it is defined.
Types of method references
- Static method reference
- Instance method reference of particular object
- Instance method reference of an arbitrary object of particular type
- Constructor reference
Static method reference
When you refer static method of Containing class. e.g. ClassName::someStaticMethodName
class MethodReferenceExample { public static int compareByAge(Employee first, Employee second) { return Integer.compare(first.age, second.age); } } ComparatorcompareByAge = MethodReferenceExample::compareByAge;
Instance method reference of particular object
When you refer to the instance method of particular object e.g. containingObjectReference::someInstanceMethodName
static class MyComparator { public int compareByFirstName(User first, User second) { return first.getFirstName().compareTo(second.getFirstName()); } public int compareByLastName(User first, User second) { return first.getLastName().compareTo(second.getLastName()); } private static void instanceMethodReference() { System.err.println("Instance method reference"); List<User> users = Arrays.asList(new User("Gaurav", "Mazra"), new User("Arnav", "Singh"), new User("Daniel", "Verma")); MyComparator comparator = new MyComparator(); System.out.println(users); Collections.sort(users, comparator::compareByFirstName); System.out.println(users); }
Instance method reference of an arbitrary object of particular type
When you refer to instance method of some class with ClassName. e.g. ClassName::someInstanceMethod;
Comparator<String> stringIgnoreCase = String::compareToIgnoreCase; //this is equivalent to Comparator<String> stringComparator = (first, second) -> first.compareToIgnoreCase(second);
Constructor reference
When you refer to constructor of some class in lambda. e.g. ClassName::new
Function<String, Job> jobCreator = Job::new; //the above function is equivalent to Function<String, Job> jobCreator2 = (jobName) -> return new Job(jobName);
You can find the full example on github.
You can also view my other article on Java 8
Comments
Post a Comment