Collectors.toMap() keyMapper -- more succinct expression?(Collectors.toMap() keyMapper——更简洁的表达方式?)
问题描述
我正在尝试为以下 Collectors.toMap()
调用中的keyMapper"函数参数提出一个更简洁的表达式:
I'm trying to come up with a more succinct expression for the "keyMapper" function parameter in the following Collectors.toMap()
call:
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(
new Function<Person, String>() {
public String apply(Person p) { return p.getLast(); }
},
Function.<Person>identity()));
似乎我应该能够使用 lambda 表达式内联它,但我想不出一个可以编译的.(我对 lambdas 很陌生,所以这不足为奇.)
It seems that I should be able to inline it using a lambda expression, but I cannot come up with one that compiles. (I'm quite new to lambdas, so that's not much of a surprise.)
谢谢.
--> 更新:
如已接受的答案中所述
Person::getLast
是我一直在寻找的,也是我尝试过的.然而,Eclipse 4.3 的 BETA_8 nightly build 是个问题——它标记为错误.从命令行编译时(我应该在发布之前完成),它起作用了.因此,是时候向 eclipse.org 提交错误了.
is what I was looking for, and is something I had tried. However, the BETA_8 nightly build of Eclipse 4.3 was the problem -- it flagged that as wrong. When compiled from the command-line (which I should have done before posting), it worked. So, time to file a bug with eclipse.org.
谢谢.
推荐答案
你可以使用 lambda:
You can use a lambda:
Collectors.toMap(p -> p.getLast(), Function.identity())
或者,更简洁地说,您可以通过 使用 方法参考::
:
or, more concisely, you can use a method reference using ::
:
Collectors.toMap(Person::getLast, Function.identity())
而不是 Function.identity
,您可以简单地使用等效的 lambda:
and instead of Function.identity
, you can simply use the equivalent lambda:
Collectors.toMap(Person::getLast, p -> p)
如果您使用 Netbeans,只要匿名类可以被 lambda 替换,您就会得到提示.
If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.
这篇关于Collectors.toMap() keyMapper——更简洁的表达方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Collectors.toMap() keyMapper——更简洁的表达方式?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01