In the last post I reviewed Java lambda expressions.They represent a concise syntax to implement functional interfaces.
Enter Java method references. They represent a concise syntax to implement functional interface using existing methods. Like with lambda expressions, referenced methods are not allowed to throw checked exceptions.
It’s simply “class-or-instance name” “::” “method name”, like
Function<String, Integer> string2Int = Integer::valueOf;
Static methods are referenced using the class name like in the example above.
Methods of a particular object are referenced using the variable name of that object:
Map<Integer, String> aMap = new HashMap<>(); Function<Integer, String> getRef = aMap::get; // call it String s = getRef.apply(42);
Instead of using an already existing object you can just state the class and a non-static method. Then the instance is an additional parameter. In the following example toURI is a method with no arguments that returns a String. The function of this method reference takes a File (the object) and returns a String:
Function<File, URI> file2Uri = File::toURI;
Constructors are references using its type and “new”:
Function<String, StringBuffer> bufferFromString = StringBuffer::new;
Here the constructor of StringBuffer with String parameter is referenced. Return type is the type of the constructor, parameters of the function are the parameters of the constructors.