Method references in Java 8 allows us to convert a call to a method
or a constructor into instance of functional interface.
For simple lambda expressions like x -> x.foo() using method
references results in expression FooClass::foo that is more
clear and readable (if this is your first encounter with method
references you may feel that they are more complicated than
lambdas - don’t worry most people go through this stage,
after a while you get used to them and you will start to
appreciate their beauty).
We will start by demonstrating how to use method references
to call instance methods.
A lambda expression of form (ObjClass obj) -> obj.method() is
equivalent to method reference ObjClass::method, for example:
Another kind of lambda expressions that can be changed to method references
has form arg -> someObj.method(arg), here the instance on which method is
called is constant but the argument changes. Let’s continue our example
This aproach also works with methods that have more than one parameter:
When we provide both instance on which to call a method and all method
arguments we may use method references too:
Using method references when working with static methods is also easy,
Now let’s move to constructor references.
Every lambda expression in form () -> new FooClass() can be
rewritten to use constructor reference as FooClass::new, for example:
We may even use constructor references to create arrays:
The last example that I want to present illustrates how
to use method references to refer to super class methods:
So after all this examples it’s your turn now, launch your favorite IDE
and write some Java code with method references!