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
21
votes
1 answer

What's the difference between Foo::new and () -> new Foo()?

I was under the impression that Foo::new is just syntactic sugar for () -> new Foo() and they should behave identically. However it seems not to be the case. Here's the background: With Java-8 I use a third party library which has an Optional
Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
20
votes
3 answers

Why does a method reference to ctor that "throws" ... throw as well?

I am looking for an elegant way to create a factory for dependency injection. In my case, the factory simply has to call a one-argument constructor. I found this answer outlining how to use a Function for such purposes. But my…
GhostCat
  • 137,827
  • 25
  • 176
  • 248
20
votes
7 answers

Difference between method reference Bound Receiver and Unbound Receiver

I am trying to use Java 8 method references in my code. There are four types of method references available. Static method reference. Instance method (bound receiver). Instance method (unbound receiver). Constructor reference. With static method…
Harmeet Singh Taara
  • 6,483
  • 20
  • 73
  • 126
20
votes
3 answers

Can Java 8 implement interface on the fly for method reference?

I learn new features of Java 8. I am playing with different examples and I have found a strange behaviour: public static void main(String[] args) { method(Test::new); } static class Test{ } private static void method(Supplier
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
20
votes
1 answer

Is there any difference between Objects::nonNull and x -> x != null?

Consider the following class: import java.util.Objects; import java.util.function.Predicate; public class LambdaVsMethodRef { public static void main(String[] args) { Predicate a = Objects::nonNull; Predicate b =…
Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
19
votes
2 answers

Java stream with method references for instanceof and class cast

Can I convert the following code using method reference? List childrenToRemove = new ArrayList<>(); group.getChildren().stream() .filter(c -> c instanceof Text) .forEach(c -> childrenToRemove.add((Text)c)); Let me give an example to…
GabrielChu
  • 6,026
  • 10
  • 27
  • 42
19
votes
6 answers

Java 8 Method Reference to non-static method

Why this doesn't work? I get compiler error "Cannot make static reference to the non static method print..." public class Chapter3 { public void print(String s) { System.out.println(s); } public static void main(String[] args) { …
andres.santana
  • 624
  • 1
  • 6
  • 13
18
votes
2 answers

Groovy equivalent of Java 8 :: (double colon) operator

What would the equivalent to Java 8 :: (double colon operator) in Groovy? I'm trying to translate this example in groovy https://github.com/bytefish/PgBulkInsert But the mapping part doesn't work the same way as Java 8: public PersonBulkInserter()…
Wavyx
  • 1,715
  • 2
  • 14
  • 23
18
votes
1 answer

How to generate a Java method reference using Groovy for testing purposes

I'm using Groovy with JUnit to test my Java code. I need to test a method foo() which takes in a java.util.function.Function public void foo(Function func){ return null; } In my normal code I call foo by passing in a method reference…
ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81
18
votes
1 answer

How to check if two method references are referencing same method?

I am trying to make list of event handlers where handler is method reference. To delete specific handler i need to find it in the list. But how can i compare code address of two method references? type TEventHandler = reference to…
Andrei Galatyn
  • 3,322
  • 2
  • 24
  • 38
17
votes
3 answers

Generic method reference type specifying before/after :: operator

What is the difference between the following method references, BiPredicate,String> contains1 = List::contains; BiPredicate,String> contains2 = List::contains; BiPredicate,String> contains3 =…
17
votes
1 answer

Java Lambda method reference not working

My original code is this: private static void onClicked(MouseEvent event) { // code to execute } // somewhere else in the program: setOnMouseClicked(event -> SomeClass.onClicked(event)); But IntelliJ says "Can be replaced with method…
Mayron
  • 2,146
  • 4
  • 25
  • 51
17
votes
1 answer

Reference to methods with different parameters in Java8

I'm wondering how does all this stuff with method references and functional interfaces works on lower level. The easiest example is where we have some List List list = new ArrayList<>(); list.add("b"); list.add("a"); list.add("c"): Now we…
swch
  • 1,432
  • 4
  • 21
  • 37
16
votes
2 answers

Why is this Java method call considered ambiguous?

I've come across a strange error message that I believe may be incorrect. Consider the following code: public class Overloaded { public interface Supplier { int get(); } public interface Processor { String process(String…
15
votes
2 answers

Is there a way to use method references for top-level functions in jshell?

Suppose I do this in jshell: jshell> void printIsEven(int i) { ...> System.out.println(i % 2 == 0); ...> } | created method printIsEven(int) jshell> List l = Arrays.asList(7,5,4,8,5,9); l ==> [7, 5, 4, 8, 5, 9] jshell>…
adashrod
  • 456
  • 2
  • 12
1 2
3
37 38