Collectors.toMap()keyMapper - 更简洁的表达方式? [英] Collectors.toMap() keyMapper -- more succinct expression?
问题描述
我正在尝试为以下 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每晚构建是问题 - 它标记为错误。从命令行编译时(我应该在发布之前完成),它可以工作。所以,是时候用eclipse.org提交bug了。
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 - 更简洁的表达方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!