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——更简洁的表达方式?
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01