home

Java 8

Method References

Shorthand if the method body you want to pass as a lambda expression is already defined elsewhere any you simply want to reference it.

Reference to a static method

ContainingClass::staticMethodName

Example without parameters

class Foo {
    static void foo() {
        // does foo!
    }
}

class ThreadTest {
    void fooTest() {
        new Thread(Foo::foo); // Shorthand for: `new Thread(() -> Foo.foo());`
    }
}

Example with parameters

import java.util.Arrays;
import java.util.List;

public class StaticMethod {

    static void consumeInteger(Integer integer) {
        // do nothing
    }

    static Integer replaceInteger(Integer integer) {
        return -integer;
    }

    public static void main(String[] args) {
        final List<Integer> integers = Arrays.asList(1, 2, 3, 4);
        integers.forEach(StaticMethod::consumeInteger);
        integers.replaceAll(StaticMethod::replaceInteger);
    }
}

Reference to an instance method of a particular object

containingObject::instanceMethodName

Example without parameters

class Foo {
    void foo() {
        // does foo!
    }
}

class ThreadTest {
    void fooTest() {
        final Foo foo = new Foo();
        new Thread(foo::foo); // Shorthand for: `new Thread(() -> foo.foo());`
    }
}

Example with parameters

import java.util.Arrays;
import java.util.List;

public class InstanceMethodOfObject {

    public void consumeString(String s) {
        // do nothing
    }

    public String replaceString(String s) {
        return s.toUpperCase();
    }

    public static void main(String[] args) {
        final List<String> myList = Arrays.asList("foo", "bar");

        final InstanceMethodOfObject myInstance = new InstanceMethodOfObject();
        myList.forEach(myInstance::consumeString);
        myList.forEach(myInstance::replaceString);
    }
}

Reference to an instance method of an arbitrary object of a particular type

ContainingType::methodName

import java.util.*;

class FooTest {
    
    int val;

    FooTest(int val) {
        this.val = val;
    }

    public void jump() {
        this.val = val * 2;
    }

    @Override
    public String toString() {
        return "FooTest: " + val;
    }
}

class Foo {
    public static void main(String[] args) {
        final List<FooTest> bars = Arrays.asList(new FooTest(2), new FooTest(4));
        bars.forEach(FooTest::jump);  // b -> b.jump()
        System.out.println(bars); // [FooTest: 4, FooTest: 8]
    }
}

Reference to a constructor

ClassName::new

import java.util.function.Function;

class Foo {
    void foo() {
        final Function<String, Integer> intConsumer = Integer::new; // Shorthand for: s -> new Integer(s);
    }
}