java 对字段的 Lambda 引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27467946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:50:37  来源:igfitidea点击:

Lambda reference to a field

javalambdajava-8

提问by Daneel S. Yaitskov

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.

我想知道如何获取对字段的 lambda 引用。我不想使用方法,因为我的领域是公共决赛。我怀疑这是不可能的,但我没有看到明显的陈述。

class A {
   public final String id;
   ...
}

Map<String, A> f(List<A> l) {
   return l.stream().collect(Collectors.toMap(A::id, Function.identity()));
}

采纳答案by Eran

You can always use a lambda expression:

您始终可以使用 lambda 表达式:

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.

我认为“方法引用”被称为这种方式是有原因的,因此仅适用于方法。

回答by Brian Goetz

It sounds like you're hoping that Java has a corresponding feature for field referencesas 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.

听起来您希望 Java 对字段引用具有相应的功能,就像对方法引用一样。但这种情况并非如此。方法引用是某一类 lambda 表达式的简写,但没有对应的字段语法。在 JSR-335 专家组审议期间探索了字段文字(此处有一些参考http://mail.openjdk.java.net/pipermail/lambda-dev/2011-November/004235.html)但未包括在内在 Java SE 8 中。