Instance Method Reference and Lambda Parameters

I think you’re looking for JLS section 15.13.3, which includes: If the form is ReferenceType :: [TypeArguments] Identifier, the body of the invocation method similarly has the effect of a method invocation expression for a compile-time declaration which is the compile-time declaration of the method reference expression. Run-time evaluation of the method invocation expression is … Read more

java.lang.NullPointerException is thrown using a method-reference but not a lambda expression

This behaviour relies on a subtle difference between the evaluation process of method-references and lambda expressions. From the JLS Run-Time Evaluation of Method References: First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference … Read more

Java 8: Difference between method reference Bound Receiver and UnBound Receiver

The idea of the unBound receiver such as String::length is you’re referring to a method of an object that will be supplied as one of the lambda’s parameters. For example, the lambda expression (String s) -> s.toUpperCase() can be rewritten as String::toUpperCase. But Bounded refers to a situation when you’re calling a method in a … Read more

Is method reference caching a good idea in Java 8?

You have to make a distinction between frequent executions of the same call-site, for stateless lambda or stateful lambdas, and frequent uses of a method-reference to the same method (by different call-sites). Look at the following examples: Runnable r1=null; for(int i=0; i<2; i++) { Runnable r2=System::gc; if(r1==null) r1=r2; else System.out.println(r1==r2? “shared”: “unshared”); } Here, the … Read more

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

The method reference System.out::println will evaluate System.out first, then create the equivalent of a lambda expression which captures the evaluated value. Usually, you would useo -> System.out.println(o) to achieve the same as the method reference, but this lambda expression will evaluate System.out each time the method will be called. So an exact equivalent would be: … Read more

Comparator.reversed() does not compile using lambda

This is a weakness in the compiler’s type inferencing mechanism. In order to infer the type of u in the lambda, the target type for the lambda needs to be established. This is accomplished as follows. userList.sort() is expecting an argument of type Comparator<User>. In the first line, Comparator.comparing() needs to return Comparator<User>. This implies … Read more