Method references is a way to pass a reference to a method, that can be invoked at a later stage, with Lambdas.
The criteria to a method reference, as with all Lambda expressions, is that it can be assigned to a functional interface.
There are 4 different kinds of method references:
Reference to a static method
When the reference is a static method in a class, for example String::valueOf in the example below.
Note, System.out returns an Object, so System.out::println is not a static method reference.
myInt = Arrays.asList(1,2,3,4,5,6,7,8,9,10); myInt.stream().map(String::valueOf).forEach(System.out::println); // Equivalent Lambda expression myInt.stream().map((i) -> String.valueOf(i)).forEach(System.out::println);
In the example, the static method reference is assigned to a Consumer interface
Reference to an instance method on class level
This is when you are referring to an method on class level. For example if we have a Person class, with a method called getAge(), that returns an int, it would be:
f1 = Person::getAge // Equivalent Lambda expression Function f2 = (Person p) -> p.getAge();
As you can see in this example, the Person::getAge is assigned to a Function interface.
Reference to an instance method of an object
Here the reference is pointing to an method on a certain object.
Person p1 = new Person(); Supplier
f1 = p1::getAge; // Equivalent Lambda expression Supplier f2 = () -> p1.getAge();
The lambda expression is assign to a Supplier interface.
A constructor reference is almost as it sounds, it calls the matching constructor on the class.
myInt = Arrays.asList(1,2,3,4,5,6,7,8,9,10); myInt.stream().map(Person::new).forEach(System.out::println); // Equivalent Lambda expression myInt.stream().map((i) -> new Person(i)).forEach(System.out::println);
In the example, it will create a new Person for each entry in the list. In this case the Person must have a constructor that takes an Integer.