O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

Using a method reference is straightforward and can be easily illustrated by a few examples for each case: 

  1. First, we have the static method reference. If a Food class has a static method, named String getFavorite(), then the lambda expression may look like this: 
         Supplier<String> supplier = Food::getFavorite;

If the Foo class has another method, named String getFavorite(int num), the lambda expression that uses it may look exactly the same:

         Function<Integer, String> func = Food::getFavorite; 

The difference is in the interface that this lambda expression implements. It allows the compiler and Java runtime to identify the method to be used. Let's look at the code. Here is the Food class: 

         public class Food{ public static ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required