Method References in Java 8

Method References in Java 8

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.


1
2
3
4
5
List<Integer> 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:


1
2
3
4
Function<Person,Integer> f1 = Person::getAge

// Equivalent Lambda expression
Function<Person,Integer> 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.


1
2
3
4
5
Person p1 = new Person();
Supplier<Integer> f1 = p1::getAge;

// Equivalent Lambda expression
Supplier<Integer> f2 = () -> p1.getAge();

The lambda expression is assign to a Supplier interface.

Constructor reference

A constructor reference is almost as it sounds, it calls the matching constructor on the class.


1
2
3
4
5
List<Integer> 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.

Leave a Reply

Your email address will not be published. Required fields are marked *