In previous tutorials, we explored how we can replace anonymous methods with lambda expression. We can possibly simplify that further in the situations where lambda expression body just call another existing method. Or more appropriately and generally speaking: if lambda's functional interface's abstract method matches another existing method signature. That applies to all kind of method, doesn't matter they are static method or instance methods. That applies to constructors as well.
We can do that by using a new operator :: (double colon)
Here's the general syntax with the simple examples for both lambda and equivalent method reference.
Method Reference Kind |
Lambda and Equivalent Method Reference Examples |
Static Method Reference |
Syntax: TheClass::someStaticMethodName Lambda:
Function<String, Integer> f = s -> Integer.parseInt(s);
System.out.println(f.apply("6")); Method Reference
Function<String, Integer> f = Integer::parseInt;
System.out.println(f.apply("6")); |
Method Reference of a Class Instance
(used for a particular instance of that class type)
|
Syntax: theObjectReference::someObjectMethod Lambda:
String s = "Some string";
Predicate<String> p = a -> s.contains(a);
System.out.println(p.test("tri")); Method Reference:
String s = "Some string";
Predicate<String> pr = s::contains;
System.out.println(pr.test("tri"));
|
Method Reference of a Class Type
(used for any arbitrary instance of that class type)
|
Syntax: ReferenceType::someObjectMethod Lambda:
Function<File, String> f = file -> file.getAbsolutePath();
System.out.println(f.apply(new File("info.txt"))); Method Reference:
Function<File, String> f = File::getAbsolutePath;
System.out.println(f.apply(new File("info.txt"))); |
Constructor Reference |
Syntax: ReferenceType::new Lambda
BiFunction<String, String, Locale> f =
(lang, code)-> new Locale(lang, code);
System.out.println(f.apply("", "US").getDisplayCountry());
Constructor Reference:
BiFunction<String, String, Locale> f = Locale::new;
System.out.println(f.apply("", "US").getDisplayCountry());
|
Example Projects
Here are more examples on method reference.
There are four main classes in following examples: StaticRefExample , ObjectRefExample , TypeRefExample and ConstructorRefExample , covering all method reference kind mentioned above. Also we used org.fluttercode.datafactory to produce test data. Dependencies and Technologies Used: - DataFactory 0.8: Library to generate data for testing.
- JDK 1.8
- Maven 3.0.4
|
|