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.
相关文章