Easy Tutorial
❮ Java Arraylist Clear Java String Intern ❯

Java 8 Method References

Java 8 New Features


Method references refer to methods by their names.

Method references can make the language constructs more compact and concise, reducing redundant code.

Method references use a double colon ::.

Below, we define 4 methods in the Car class as examples to distinguish between 4 different types of method references in Java.

package com.tutorialpro.main;

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

class Car {
    // Supplier is a JDK 1.8 interface, used here with lambda
    public static Car create(final Supplier<Car> supplier) {
        return supplier.get();
    }

    public static void collide(final Car car) {
        System.out.println("Collided " + car.toString());
    }

    public void follow(final Car another) {
        System.out.println("Following the " + another.toString());
    }

    public void repair() {
        System.out.println("Repaired " + this.toString());
    }
}

-

Constructor Reference: Its syntax is Class::new, or more generally Class<T>::new. Example:

final Car car = Car.create( Car::new );
final List< Car > cars = Arrays.asList( car );

-

Static Method Reference: Its syntax is Class::static_method. Example:

cars.forEach( Car::collide );

-

Reference to a Method of an Arbitrary Object of a Particular Type: Its syntax is Class::method. Example:

cars.forEach( Car::repair );

-

Reference to a Method of a Particular Object: Its syntax is instance::method. Example:

final Car police = Car.create( Car::new );
cars.forEach( police::follow );

Method Reference Example

Enter the following code in the Java8Tester.java file:

Java8Tester.java File

import java.util.List;
import java.util.ArrayList;

public class Java8Tester {
   public static void main(String args[]){
      List<String> names = new ArrayList();

      names.add("Google");
      names.add("tutorialpro");
      names.add("Taobao");
      names.add("Baidu");
      names.add("Sina");

      names.forEach(System.out::println);
   }
}

In the example, we reference the System.out::println method as a static method.

Executing the script will produce the following output:

$ javac Java8Tester.java 
$ java Java8Tester
Google
tutorialpro
Taobao
Baidu
Sina

Java 8 New Features

❮ Java Arraylist Clear Java String Intern ❯