Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Thanks.

--> Update:

As noted in the accepted answer

Person::getLast 

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.

Thanks.

like image 875
pfurbacher Avatar asked Oct 08 '13 17:10

pfurbacher


People also ask

What does Collectors toMap do?

The toMap() method is a static method of Collectors class which returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

How do you collect a stream from a map?

Method 1: Using Collectors.toMap() Function The Collectors. toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key.


2 Answers

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.

like image 136
assylias Avatar answered Sep 20 '22 14:09

assylias


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

like image 37
aepurniet Avatar answered Sep 19 '22 14:09

aepurniet