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())); }
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With