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
33
votes
7 answers

What does "an Arbitrary Object of a Particular Type" mean in java 8?

In Java 8 there is "Method Reference" feature. One of its kind is "Reference to an instance method of an arbitrary object of a particular type" http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html#type Can someone explain what…
Roman Ivanov
  • 2,477
  • 3
  • 20
  • 31
31
votes
4 answers

How to use a method reference on a static import?

When using map functions in java I can do the following: import com.example.MyClass; someStream.map(MyClass::myStaticMethod) but in my project we sometimes use static imports, how can I reference the myStaticMethod when the import is static? I…
Richard Deurwaarder
  • 2,023
  • 1
  • 26
  • 40
29
votes
2 answers

The target type of this expression must be a functional interface in MethodReferences

Why does the following code not compile. Consumer con = (s) -> System.out::println; It says The target type of this expression must be a functional interface even though Consumer is a Functional Interface. The below works just fine. Consumer con2…
HariJustForFun
  • 521
  • 2
  • 8
  • 17
29
votes
2 answers

Invalid constructor reference when using local class?

Given the following code: package com.gmail.oksandum.test; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { } public void foo() { class LocalFoo { …
Rocoty
  • 406
  • 5
  • 11
27
votes
4 answers

The type org.eclipse.jdt.annotation.NonNull cannot be resolved. It is indirectly referenced from required .class files

When I use the Java 8 method reference double colon operator (::) with new operator (e.g. MyType::new), I get this error in Eclipse of Spring Tool suite (STS): The type org.eclipse.jdt.annotation.NonNull cannot be resolved. It is indirectly…
luboskrnac
  • 23,973
  • 10
  • 81
  • 92
27
votes
2 answers

What is the equivalent lambda expression for System.out::println

I stumbled upon the following Java code which is using a method reference for System.out.println: class SomeClass { public static void main(String[] args) { List numbers = Arrays.asList(1,2,3,4,5,6,7,8,9); …
Steve
  • 889
  • 1
  • 12
  • 26
27
votes
3 answers

Java 8 Method references called on a local variable

I am in the process of learning Java 8 and I came across something that I find a bit strange. Consider the following snippet: private MyDaoClass myDao; public void storeRelationships(Set> relationships) { …
Emil D
  • 1,864
  • 4
  • 23
  • 40
25
votes
2 answers

Why does invokeLater execute in the main thread?

I just encountered this "bug", but I'm not sure if this is intended: Code: public static Object someMethod(){ assert SwingUtilities.isEventDispatchThread(); return new Object(); } public static void main(String[] args){ …
RoiEX
  • 1,186
  • 1
  • 10
  • 37
25
votes
3 answers

Why did Java 8 introduce a new "::" operator for method references?

In Java 8 method references are done using the :: operator. For Example // Class that provides the functionality via it's static method public class AddableUtil { public static int addThemUp(int i1, int i2){ return i1+i2; } } // Test…
ShaggyInjun
  • 2,880
  • 2
  • 31
  • 52
24
votes
3 answers

Access method of outer anonymous class from inner anonymous class

I instantiate an anonymous class with a method that instantiates another anonymous class, and from this inner anonymous class I want to call a method belonging to the outer anonymous class. To illustrate it, suppose I have this interface: interface…
Rulle
  • 4,496
  • 1
  • 15
  • 21
24
votes
3 answers

Cast java.util.function.Function to Interface

Example In this (simplified) example I can create my MyInterface-object by using a method reference to apply, but casting directly doesn't work. @Test public void testInterfaceCast(){ Function func = Integer::parseInt; …
tomaj
  • 1,570
  • 1
  • 18
  • 32
24
votes
3 answers

What's the difference between instance method reference types in Java 8?

So Java 8 introduces method references and the docs describe the four types. My question is what's the difference between the two instance types? Reference to an instance method of a particular object. Reference to an instance method of an…
Toby
  • 9,523
  • 8
  • 36
  • 59
23
votes
2 answers

Composition of method reference

This is related to this question: How to do function composition? I noticed that a method reference can be assigned to a variable declared as Function, and so I assume it should have andThen or compose function, and hence I expect that we can…
justhalf
  • 8,960
  • 3
  • 47
  • 74
22
votes
3 answers

Unexpected behavior when using Comparator.comparing(HashMap::get) as a comparator

Doing the exercise 'Literature' on https://java-programming.mooc.fi/part-10/2-interface-comparable I discovered a very strange behavior when trying to sort key-value pairs in a HashMap, without copying anything to a TreeMap. I was supposed to add…
Milos Cupara
  • 231
  • 2
  • 5
22
votes
3 answers

Limitations of forEach with instance method references in Java 8

Assume I have the following functional interface: public interface TemperatureObserver { void react(BigDecimal t); } and then in another class an already filled-in ArrayList of objects of type TemperatureObserver. Assuming that temp is a…
Temp Agilist
  • 233
  • 1
  • 2
  • 8
1
2
3
37 38