For example, I have some class Person
class Person {
private String firstName;
private String lastName;
private String street;
...
}
Also, I have a List<Person> personList
that contains some Person
objects. The goal is to put these objects to Map<Person, Timer> personMap
as keys and add new Timer()
objects as values. So each Person
has one Timer()
.
I'm, trying to do next:
personMap = personList.stream().collect(toMap(person -> person, new Timer()));
But compiler says: there is no instance(s) of type variable(s) T, U exist so that Timer conforms to Function<? super T, ? extends U>
. I've been searching here Java 8 List into Map but it doesn't work for me.
What am I missing? What's wrong with Timer()
class?
You have to provide a function for both key and vaue to the Collectors::toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
where:
keyMapper - a mapping function to produce keys
valueMapper - a mapping function to produce values
You need:
Map<Person, Timer> personMap = personList.stream()
.collect(Collectors.toMap(
person -> person, // Function to create a key
person -> new Timer())); // Function to create a value
For better understanding, here are lambdas represented as anonymous classes using the very same Collector:
new ArrayList<Person>().stream().collect(Collectors.toMap(
new Function<Person, Person>() { // Function to create a key
@Override
public Person apply(Person person) {
return person; // ... return self
}},
new Function<Person, Timer>() { // Function to create a value
@Override
public Timer apply(Person person) {
return new Timer(); // ... return a new Timer
}}
));