Collectors.toMap用方法引用可编译,Lambda标识函数为何报错?
ArrayList转LinkedHashMap的代码报错原因分析
我有一个ArrayList<Employee>,想要将其转换为LinkedHashMap<String, Integer>,下面两段代码一段报错、一段正常运行,二者的核心区别如下:
报错信息
Bad return type in lambda expression: U cannot be converted to Employee
报错代码
LinkedHashMap<String, Integer> collect = employees.stream() .sorted(Comparator.comparing(Employee::getName).reversed()) .collect(Collectors.toMap(Employee::getName, x-> x, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
可行代码
LinkedHashMap<String, Integer> collect = employees.stream() .sorted(Comparator.comparing(Employee::getName).reversed()) .collect(Collectors.toMap(Employee::getName, Employee::getId, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
二者区别
核心差异在Collectors.toMap的第二个参数(value映射函数):
- 报错代码中使用
x -> x,意味着把整个Employee对象作为Map的value,但你声明的LinkedHashMap<String, Integer>要求value类型为Integer,类型完全不匹配,因此编译器抛出类型转换错误。 - 可行代码中使用
Employee::getId,这是方法引用,会从每个Employee对象中提取id属性(类型为Integer),正好匹配Map的value泛型要求,所以编译运行都正常。
简单说:你要的是"姓名-ID"的映射,就得明确指定取ID作为value,而不是把整个员工对象塞进去。
内容的提问来源于stack exchange,提问作者user3310115
相关产品推荐
相关产品推荐

