Lambda reference to a field

▼魔方 西西 提交于 2020-01-12 11:09:54

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!