Questions tagged [method-reference]

Method references, introduced in Java 8, are a way to refer to a method by its name instead of using a lambda expression.

Method references were introduced in alongside lambda expressions.

The programmer can use a method reference as a syntactic sugar for a lambda expression that would merely call that method, when its signature is compatible with the type.

The syntax of a method reference closely matches a method invocation expression, but with a double colon (::) replacing the dot (.).

// static method reference:
ToIntFunction<String> parseInt = Integer::parseInt;
int i = parseInt.applyAsInt("123");

// instance method reference:
Consumer<Object> println = System.out::println;
println.accept("Hello world!");

// constructor method reference:
Supplier<Object> newObject = Object::new;
Object o = newObject.get();

// array creation method reference:
IntFunction<Number[]> newArray = Number[]::new;
Number[] a = newArray.apply(10);

When working with generics, type arguments may be provided explicitly or inferred.

Supplier<List<String>> listSupplier;

// explicit type argument for a class:
listSupplier = ArrayList<String>::new;
// inferred type argument for a class:
listSupplier = LinkedList::new;
//             ^^^^^^^^^^
//             note: not a raw type in this context!
//             LinkedList<String> will be inferred.

// explicit type argument for a method:
listSupplier = Collections::<String>emptyList;
// inferred type argument for a method:
listSupplier = Collections::emptyList;

See also:

567 questions
15
votes
1 answer

SONAR: Replace this lambda with a method reference

Sonar tells me "Replace this lambda with a method reference" public class MyClass { private List createSomeValues(List anyList) { return anyList // .stream() // .map(anything ->…
Chris311
  • 3,794
  • 9
  • 46
  • 80
14
votes
5 answers

Method reference in Java 8

public class Car { private int maxSpeed; public Car(int maxSpeed) { this.maxSpeed = maxSpeed; } public int getMaxSpeed() { return maxSpeed; } } We can sort a list of cars by, Car carX = new Car(155); …
saravana_pc
  • 2,607
  • 11
  • 42
  • 66
14
votes
2 answers

Why does this Java 8 method reference compile?

I'm currently diving deeper into Java 8 features like Lambdas and method references. Playing around a bit brought me to the following example: public class ConsumerTest { private static final String[] NAMES = {"Tony", "Bruce", "Steve", "Thor"}; …
pklndnst
  • 726
  • 2
  • 10
  • 27
14
votes
2 answers

Java 8 reference to a static method vs. instance method

say I have the following code public class A { int x; public boolean is() {return x%2==0;} public static boolean is (A a) {return !a.is();} } and in another class... List a =…
Will Sherwood
  • 1,484
  • 3
  • 14
  • 27
13
votes
2 answers

Java 8 method references and overridden methods

I've been using lambdas and method references in Java 8 for a while and there is this one thing I do not understand. Here is the example code: Set first = Collections.singleton(1); Set second = Collections.singleton(2); …
Elopteryx
  • 285
  • 1
  • 5
  • 10
13
votes
2 answers

Why 'T.super.toString()' and 'super::toString' use a synthetic accessor method?

Consider the following set of expressions: class T {{ /*1*/ super.toString(); // direct /*2*/ T.super.toString(); // synthetic Supplier s; /*3*/ s = super::toString; // synthetic /*4*/ s = T.super::toString; //…
charlie
  • 1,478
  • 10
  • 20
13
votes
1 answer

Method reference to array clone() causes NoClassDefFoundError: Array

When I run this code List list = Arrays.asList(new int[]{1, 2, 3}, new int[]{4, 5}); int[][] arr = list.stream().map(j -> j.clone()).toArray(int[][]::new); System.out.println(Arrays.deepToString(arr)); it works as expected and I get the…
Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
13
votes
1 answer

Invoking toString via method reference in Java 8

What am I missing? Why do I have to use Object::toString below and not Integer::toString? Does it have anything to do with type erasure with generics? Arrays.asList(1,2,3).stream().map(Integer::toString).forEach(System.out::println); //Won't…
sat
  • 5,489
  • 10
  • 63
  • 81
13
votes
2 answers

Why Comparator.comparing doesn't work with String::toLowerCase method reference?

I am trying to sort an array of Strings by reverse order (ignoring case), without modifying it, and just printing it. So I am using Java8 stream. But I can't manage to do it. Here is my attempt : package experimentations.chapter02; import…
loloof64
  • 5,252
  • 12
  • 41
  • 78
12
votes
4 answers

How to bind a Java Supplier to an instance of an object?

How can I bind a Java Supplier to an existing instance of an Object? For example, if I want to write my own compareTo() method with this header: public static int myCompareTo(Object o1, Object o2, Supplier supplier) {...} I want be able…
12
votes
3 answers

Static reference ( with :: ) to a method returning an interface

I have several predifined static "processors" implementing the same method, for example: default double process(double num){ Sample : public class Test { public static void main(String[] args) { test(Test::processor1, 1d); …
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50
12
votes
3 answers

Method Reference. Cannot make a static reference to the non-static method

Can someone explain to me, why passing a non-static method-reference to method File::isHidden is ok, but passing method reference to a non-static method MyCass::mymethod - gives me a "Cannot make a static reference to the non-static method"…
Skip
  • 6,240
  • 11
  • 67
  • 117
12
votes
1 answer

Is it possible to convert method reference to MethodHandle?

Is it possible to convert a method reference (e.g. SomeClass::someMethod) to a MethodHandle instance? I want the benefits of compile-time checking (ensuring that the class and method exists) as well as the ability to introspect the method using the…
Gili
  • 86,244
  • 97
  • 390
  • 689
11
votes
4 answers

Can we get a method name using java.util.function?

I tried to do: public class HelloWorld { public static void main(String... args){ final String string = "a"; final Supplier supplier = string::isEmpty; System.out.println(supplier); } } I…
Marco Sulla
  • 15,299
  • 14
  • 65
  • 100
11
votes
3 answers

Java Compile Error: Method reference in combination with overloading

I have the following class with an overloaded method: import java.util.ArrayList; import java.util.concurrent.Callable; public abstract class Test { public void test1 () { doStuff (ArrayList::new); // compilation error } public void…