In this answer I attempted to create a static utility method to make a List
into a Map
:
public static Map toMa
Your last line calls the method toMapBy
in which the compiler infers the type Student
for T
. So it obviously returns a List
.
But generics aren't covariant!
That means, you cannot assign a List
to a variable of type List
, because they are not in a subtype relationship.
The solution is to use the subtype form:
Map peopleById2 = toMapBy(students, Student::getId); // no compiler error