Collectors.toMap() keyMapper -- more succinct expression?
Solution 1:
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.
Solution 2:
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(...)
Solution 3:
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)
);