ToMap() keyMapper ——更简洁的表达式?

我试图在下面的 Collectors.toMap()调用中为“ keyMapper”函数参数提供一个更简洁的表达式:

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 还是个新手,所以这并不令人惊讶。)

谢谢。

- > 更新:

正如公认的答案所指出的

Person::getLast

是我一直在寻找的,也是我曾经尝试过的。然而,Eclipse 4.3的 BETA _ 8夜间版本存在问题——它标记为错误。当从命令行编译时(在发布之前我就应该这样做) ,它起作用了。所以,是时候向 eclipse.org 发布一个 bug 了。

谢谢。

223940 次浏览
List<Person> roster = ...;


Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

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())

and instead of Function.identity, you can simply use the equivalent lambda:

Collectors.toMap(Person::getLast, p -> p)

If you use Netbeans you should get hints whenever an anonymous class can be replaced by a lambda.

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(),
p -> p,
(person1, person2) -> person1+";"+person2)
);