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
11
votes
5 answers

Concise way of composing Java method references?

Given some Java 8 method functions: class Foo { Bar getBar() {} } class Bar { Baz getBaz() {} } A composition of the two accessors looks like: Function getBarFromFoo = Foo::getBar; Function getBazFromBar =…
Gene
  • 46,253
  • 4
  • 58
  • 96
11
votes
10 answers

What does "String[]::new" mean?

I'm learning how to use stream, and I get a problem with this method. public static String[] inArray(String[] array1, String[] array2) { return Arrays.stream(array1) .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str))) …
xshe2
  • 147
  • 1
  • 1
  • 6
11
votes
3 answers

How to suitably compose Predicate and Function in a Java function?

The purpose is to create a new Predicate usable in a stream filter : myCollectionOfElement .stream() .filter( …
fdelsert
  • 768
  • 1
  • 10
  • 22
11
votes
6 answers

Passing non final objects to method references

What is the explanation that s.get() returns "ONE" the second time as well? String x = "one"; Supplier s = x::toUpperCase; System.out.println("s.get() = " + s.get()); x = "two"; System.out.println("s.get() = " + s.get()); Update: Compare it…
11
votes
1 answer

Java 8's missing parameters when using ::

Java 8's :: enables method referencing via method name alone. protected Object loadBeanController(String url) throws IOException { loader = new FXMLLoader(getClass().getResource(url)); ApplicationContext context =…
Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
11
votes
4 answers

Please Explain Java 8 Method Reference to instance Method using class name

public interface MyFunc { boolean func(T v1, T v2); } public class HighTemp { private int hTemp; HighTemp(){ } public HighTemp(int ht) { this.hTemp = ht; } boolean sameTemp(HighTemp ht2){ return…
11
votes
2 answers

Syntax for specifying a method reference to a generic method

I read the following code in "Java - The beginner's guide" interface SomeTest { boolean test(T n, T m); } class MyClass { static boolean myGenMeth(T x, T y) { boolean result = false; // ... return…
kevin gomes
  • 1,775
  • 5
  • 22
  • 30
10
votes
2 answers

Java compiler: How can two methods with the same name and different signatures match a method call?

I have this class called Container: public class Container { private final Map map = new HashMap<>(); public void put(String name, Object value) { map.put(name, value); } public Container with(String name,…
A4L
  • 17,353
  • 6
  • 49
  • 70
10
votes
2 answers

Call method on chosen method reference inline

I have the following program that fails to compile: Just block 1 compiles fine and works as expected - I can conditionally select an object and call a method on it inline. Just block 2 also compiles fine and works as expected - I can conditionally…
iobender
  • 103
  • 5
10
votes
2 answers

kotlin - Pass method reference to function

Let's say I have the following Java class: public class A { public Result method1(Object o) {...} public Result method2(Object o) {...} ... public Result methodN(Object o) {...} } Then, in my Kotlin code: fun myFunction(...) { val…
piotrek
  • 13,982
  • 13
  • 79
  • 165
10
votes
3 answers

Replace lambda with method reference in flatMap during array mapping

Say we have a Customer class: public class Customer { private Car[] cars; // getter, setter, constructor } and collection of customers which we need to map on cars. Currently I'm doing it somehow like this: Collection customers =…
Sasha Shpota
  • 9,436
  • 14
  • 75
  • 148
10
votes
2 answers

Java 8 - how do I declare a method reference to an unbound non-static method that returns void

Here's a simple class that illustrates my problem: package com.example; import java.util.function.*; public class App { public static void main(String[] args) { App a1 = new App(); BiFunction f1 = App::m1; …
John Calcote
  • 793
  • 1
  • 8
  • 15
10
votes
3 answers

Comparator.comparing(...) throwing non-static reference exception while taking String::compareTo

Below are the two lines of my code snippet: List listDevs = Arrays.asList("alvin", "Alchemist", "brutus", "larsen", "jason", "Kevin"); listDevs.sort(Comparator.comparing(String::length)); //This works…
Vikrant
  • 1,809
  • 1
  • 13
  • 18
10
votes
1 answer

Types in a LambdaMetaFactory

I get an exception when I call metafactory. It says: java.lang.invoke.LambdaConversionException: Incorrect number of parameters for instance method invokeVirtual my.ExecuteTest$AProcess.step_1:()Boolean; 0 captured parameters, 0…
towi
  • 21,587
  • 28
  • 106
  • 187
10
votes
2 answers

How does Java 8 know which String::compareTo method reference to use when sorting?

How does Java know which String::compareTo method reference to use when calling Collections.sort(someListOfStrings, String::compareTo);? compareTo is not static and it needs to know the value of the "left hand side" of the comparison.
stantonk
  • 1,922
  • 1
  • 18
  • 24