Collectors.toMap () keyMapper - a more concise expression?

I am trying to come up with a more concise expression for the parameter parameter of the "keyMapper" function in the following call to "Collectors.toMap ()":

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 like I should be able to embed it with a lambda expression, but I can't think of a compilation. (I'm completely new to lambdas, so no wonder.)

Thank.

-> Update:

As noted in the accepted answer

 Person::getLast 

this is what i was looking for and this is what i tried. However, the BETA_8 nightly build of Eclipse 4.3 was a problem - she noted that it was wrong. When compiling from the command line (which I had to do before publishing) this worked. So, time to download the error from eclipse.org.

Thank.

+42
java collections lambda java-8 java-stream
Oct 08 '13 at 17:57
source share
3 answers

You can use lambda:

 Collectors.toMap(p -> p.getLast(), Function.identity()) 

or, more briefly, you can use the link with ::

 Collectors.toMap(Person::getLast, Function.identity()) 

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

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

If you are using Netbeans, you should be prompted when an anonymous class can be replaced with lambda.

+107
Oct 08 '13 at
source share
 List<Person> roster = ...; Map<String, Person> map = roster .stream() .collect( Collectors.toMap(p -> p.getLast(), p -> p) ); 

which would be a translation, but I havent run this or used the API. most likely you can replace p → p with Function.identity (). and statically import toMap (...)

+19
Oct 08 '13 at 19:41
source share

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

 Map<String, Person> map = roster .stream() .collect( Collectors.toMap(p -> p.getLast(), p -> p, (person1, person2) -> person1+";"+person2) ); 
+4
Nov 30 '16 at 10:45
source share



All Articles