Close

Method References

[Updated: Feb 10, 2016, Created: Dec 9, 2015]

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 On Class Instance
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 On 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
Synatx:
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. In our examples, we try to be close to practical scenarios but to fully focus on the current topic, we prefer to skip things like properer workflow and modularity etc. For example in the following exmaple, DataService.java should be interface based and there should be some service look up or dependency injection approach.

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

Method Reference Example Select All Download
  • java-method-ref-examples
    • src
      • main
        • java
          • com
            • logicbig
              • ref
              • service

See Also