pfurbacher pfurbacher - 1 year ago 181
Java Question

Collectors.toMap() keyMapper -- more succinct expression?

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 =
new Function<Person, String>() {
public String apply(Person p) { return p.getLast(); }

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


--> Update:

As noted in the accepted answer


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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download