在this answer我试图创建一个静态实用方法,使一个List
成Map
:通用静态方法限制类型太多
public static <K, T> Map<K, T> toMapBy(List<T> list,
Function<? super T, ? extends K> mapper) {
return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}
它工作得很好。但是,我发现该方法不能与list.stream().collect(...)
表达式在所有相同的上下文中使用。该方法不够灵活。
List<Student> students = Arrays.asList();
Map<Long, Student> studentsById1 = students.stream()
.collect(Collectors.toMap(Student::getId, Function.identity()));
Map<Long, Student> studentsById2 = toMapBy(students, Student::getId);
Map<Long, Person> peopleById1 = students.stream()
.collect(Collectors.toMap(Student::getId, Function.identity()));
Map<Long, Person> peopleById2 = toMapBy(students, Student::getId); // compile error!
在这个例子中,是Student
的Person
亚型和具有getId
方法,它返回一个Long
。
最后一条语句失败,出现incompatible types: inference variable T has incompatible bounds ...
(JDK 1.8.0_25)。有没有一种方法来定义类型参数,以便静态方法与其包含的表达式在相同的上下文中工作?
[is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-的-listanimal - 为什么 - ARENT-Java类,泛型隐-p)。 'Map'不能被引用到返回的'Map '。也许考虑使用'Map '。 –
Pshemo
2014-11-01 18:05:32
如果你可以使用'Map'Map '的实例,那么这意味着通过这样的引用你可以在这张地图上放置任何类型的人,不仅是学生(换句话说泛型不是协变的)。 –
Pshemo
2014-11-01 18:15:04