【发布时间】:2021-05-22 23:51:26
【问题描述】:
我想使用 Collectors.toMap() 函数根据性别对 Person 对象进行分组,如下所述,但这并不像我预期的那样工作。
class Person{
private Integer id;
private String gender;
private String name;
public String getGender(){
return gender;
}
public Person(Integer id, String gender, String name){
this.id=id;
this.gender=gender;
this.name=name;
}
}
public static void main(String[]args){
List<Person> persons=new ArrayList<>();
persons.add(new Person(1,"Man","John"));
persons.add(new Person(2,"Man","Steve"));
persons.add(new Person(3,"Women","Linda"));
persons.add(new Person(4,"Man","Bill"));
persons.add(new Person(5,"Women","Siti"));
persons.add(new Person(6,"Man","Buzzer"));
Map<String,List<Person>> filtered=persons
.stream()
.collect(Collectors.toMap(Person:getGender:Function.identity()));
}
错误提示
不兼容的类型:推理变量 U 具有不兼容的边界 等式约束:列表 下界:Person,T#2,T#1 其中 U,T#1,K,T#2 是类型变量: U 扩展方法中声明的对象
中声明的对象toMap(Function super T#1,? >> extends K>,Function super T#1,? extends U>) T#1 扩展方法中声明的对象 toMap(Function super T#1,?> extends K>,Function super T#1,? extends U>) K 扩展方法中声明的对象 toMap(Function super T#1,? > 扩展 K>,函数) T#2 扩展了在方法 identity()
中声明
collect(Collector super T,A,R>) 的类型错误 其中 R,A,T 是类型变量: R 扩展了在方法 collect(Collector super T,A,R>) 中声明的对象 A extends Object 在方法 collect(Collector super T,A,R>)
谁能解释这个错误?
【问题讨论】:
标签: java