您可能需要注意重复键。如果键是重复的,则会抛出IllegalStateException。
试试这个重复键:
// This THROWS an Exception. DO NOT DO IF DUPLICATE KEYS
// Map<PersonKey, Person> mapThrowException = list.stream().collect(
// Collectors.toMap(p -> new PersonKey(p.first, p.last), p -> p));
// if duplicate key exists for two persons, choose the first person
Map<PersonKey, Person> properMap =
list.stream().collect(
Collectors.toMap(
p -> new PersonKey(p.first, p.last),
p -> p, (person1, person2) -> person1 ));
或者您可以使用为此目的提供的Function.identity()。
Map<PersonKey, Person> properMap2 =
list.stream().collect(
Collectors.toMap(
p -> new PersonKey(p.getFirst(), p.getLast()),
Function.identity(),
(person1, person2) -> person1 ));
如果要求按键分组并且不删除任何值(在重复键的情况下),请使用groupingBy(如@WJS 建议的那样):
Map<PersonKey, List<Person>> properMapWithListForDuplicateKeys =
list.stream().collect(
Collectors.groupingBy(
p -> new PersonKey(p.getFirst(), p.getLast())));