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

double colon :: java 8 how does the following even work

I came across the following code: List invFieldsLst = new ArrayList<>(); InvListener listener = invFieldsLst::add; The following interface: public interface InvListener { void test(Fields fields); } How does the double :: even work? I…
user1555190
  • 2,803
  • 8
  • 47
  • 80
0
votes
1 answer

NoClassDefFoundError with Java 8 method reference

I am running Android instrumentation tests on an emulator on Travis CI. The following test case invokes a helper method per method reference: @Test public void testGetLowEmissionZones_worksAtAll() { // ... …
JJD
  • 50,076
  • 60
  • 203
  • 339
0
votes
1 answer

Kotlin a member reference to return the object itself

Is there a way to write a member/method reference to return the object itself in Kotlin? That is to say, it can simplify and replace the following lambda: { it }
Shreck Ye
  • 1,591
  • 2
  • 16
  • 32
0
votes
1 answer

Registering remote procedures with autobahn java

The standard way of registering procedures in autobahn-java is: CompletableFuture order_to_produce = session.register(prefix + "order_to_produce", this::order_to_produce); order_to_produce.thenAccept(registration ->…
0
votes
0 answers

Mock method invocation with Method Reference as Param

Is there any way to mock something like this: when(mock.methodCall(Class::gettter)).willReturn(...) when(mock.methodCall(Class::gettter2)).willReturn(...) Header for methodCall methodCall(Function function) When I use…
Krzysztof Mazur
  • 568
  • 2
  • 13
0
votes
0 answers

Why does the order of invoking impact on the execution time?

Context So I am playing with the code related to How slow are Java exceptions? by adding some method references to it. The modified code is below /** * [https://stackoverflow.com/questions/299068/how-slow-are-java-exceptions] * * The original…
0
votes
0 answers

How list.sort/Collections.sort is accepting my custom comparator ? [java 8]

I am new in Java 8, went through few tutorials and docs. But couldn't get all the doubts cleared. While using sort operation of a list or collections class, we need(or not) to pass the comparator to get the desired sorting. but with Java 8, even we…
gaurav kumar
  • 129
  • 2
  • 14
0
votes
2 answers

SonarLint: Replace this lambda with a method reference

I have a collection that contains a list of errors. I wanted to group these by a key (UUID UserId). For this I have copied the code from this answer: https://stackoverflow.com/a/30202075/4045364 Collection filterErrors = new…
Rence
  • 2,900
  • 2
  • 23
  • 40
0
votes
1 answer

Put reflect.Method to a functional interface

For example, I have a class with a method public class SomeClass { public void someMethod(Object arg) { //some code } } And I obtained method through reflection in another class: SomeClass instance = new SomeClass(); Method method…
0
votes
0 answers

Null reference in Java 8 function reference but not in lambda abstraction

I've recently encountered another NullPointerException in Java. It took me quite some time to figure it out, but in the end I found the problem. Here's the thing: it's a Java 8 method reference that is causing the exception. When I convert that…
KnorpelSenf
  • 390
  • 1
  • 3
  • 10
0
votes
2 answers

Local classes with Lambda expressions

As I tested, the below code executes without any issues. But I could not understand the logic. Can someone please explain? public static void main(String[] args) { List london = new ArrayList<>(Arrays.asList("Chinatown","Croydon","Eden…
0
votes
0 answers

SonarLint Squid:S1612 with AddActionListener on Eclipse Oxygen

First, all my action listeners call a private method in my class. They are in the initComponents method that is not static, and so are the private method called by the action listeners. The project was on Java 1.5 and moved to Java 1.8. SonarLint…
0
votes
1 answer

How can I suppress rawType of method reference?

I have a method looks like this. public & Some> void setOther(final E some) { setOther(ofNullable(some).map(e -> e.name()).orElse(null); } Now IntelliJ suggests to use a method reference for e -> e.name() part. And I changed…
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
0
votes
2 answers

Java: compilation error with generic function reference

Could someone help me to fix this compilation error, please? I 'd like to define a map method in the generic interface called Suite and use it like this: Suite < Integer > suite2 = Suite.from("34", "78",…
Toto
  • 9
  • 4
0
votes
2 answers

How to use (or replace) java 8 functional interface with Android API below 24?

I am developing an android app (minSdkVersion: 23). In my signIn method, I make a call like that: RequestClass.doRequestWithApi(this.getApplicationContext(), this.TAG, dataToPass, this::getMyAccount); And here is the doRequestWithApi method: public…
fdieval
  • 99
  • 1
  • 6