问题
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()));
}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/27467946/lambda-reference-to-a-field