您必须同时提供Collectors::toMap(Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper)的键和值的功能,其中:
keyMapper – a mapping function to produce keys
valueMapper – a mapping function to produce values
你需要:
Map personMap = personList.stream()
.collect(Collectors.toMap(
person -> person, // Function to create a key
person -> new Timer())); // Function to create a value
为了更好地理解,以下是使用同一收集器将lambda表示为匿名类的情况:
new ArrayList().stream().collect(Collectors.toMap(
new Function() { // Function to create a key
@Override
public Person apply(Person person) {
return person; // ... return self
}},
new Function() { // Function to create a value
@Override
public Timer apply(Person person) {
return new Timer(); // ... return a new Timer
}}
));