通用静态方法过多地约束类型 [英] Generic static method constrains types too much
问题描述
在此答案中,我尝试创建一个静态实用程序方法来生成列表
进入地图
:
In this answer I attempted to create a static utility method to make a List
into a 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(...)
表达式相同的上下文中使用。该方法不够灵活。
It works just fine. However, I found that the method cannot be used in all the same contexts as the list.stream().collect(...)
expression. The method isn't as flexible.
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!
在此示例中,学生
是一个子类型 Person
并且有一个 getId
方法,返回 Long
。
In this example, Student
is a subtype of Person
and has a getId
method that returns a Long
.
最后一个语句失败,不兼容类型:推理变量T具有不兼容的边界...
(JDK 1.8。 0_25)。有没有办法定义类型参数,以便静态方法在与它包含的表达式相同的上下文中工作?
The last statement fails with incompatible types: inference variable T has incompatible bounds ...
(JDK 1.8.0_25). Is there a way to define the type parameters so that the static method will work in the same contexts as the expression it contains?
推荐答案
您可以为地图的值添加类型参数,以便它们可以与T不同:
You could add a type parameter for the values of the map so they can be different from T:
public static <K, V, T extends V> Map<K, V> toMapBy(List<T> list,
Function<? super T, ? extends K> mapper) {
return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}
这篇关于通用静态方法过多地约束类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!