Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda reference to a field

I'd like to know how to get lambda reference to a field. I don't want to use a method because my field is public final. I suspect this is impossible but I don't see an obvious statement.

class A {    public final String id;    ... }  Map<String, A> f(List<A> l) {    return l.stream().collect(Collectors.toMap(A::id, Function.identity())); } 
like image 581
Daniil Iaitskov Avatar asked Dec 14 '14 09:12

Daniil Iaitskov


People also ask

Can lambda statements return a value?

The lambda must contain the same number of parameters as the delegate type. Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter. The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

How do you reference a method using parameters?

To make the code clearer, you can turn that lambda expression into a method reference: Consumer<String> c = System. out::println; In a method reference, you place the object (or class) that contains the method before the :: operator and the name of the method after it without arguments.

What does -> mean in Java?

When more than one parameter is passed, they are separated by commas. To support lambdas, Java has introduced a new operator “->”, also known as lambda operator or arrow operator. This arrow operator is required because we need to syntactically separate the parameter from the body.


2 Answers

It sounds like you're hoping that Java has a corresponding feature for field references as it does for method references. But this is not the case. Method references are shorthand for a certain category of lambda expressions, but there is no corresponding syntax for fields. Field literals were explored during the JSR-335 Expert Group deliberation (there is some reference to it here http://mail.openjdk.java.net/pipermail/lambda-dev/2011-November/004235.html) but were not included in Java SE 8.

like image 146
Brian Goetz Avatar answered Sep 21 '22 09:09

Brian Goetz


You can always use a lambda expression:

return l.stream().collect(Collectors.toMap(a -> a.id, Function.identity())); 

I think that "method references" are called this way for a reason, and therefore apply only for methods.

like image 43
Eran Avatar answered Sep 20 '22 09:09

Eran