Java Stream中toMap转SortedMap时类型不匹配问题求助
解决Java Stream转SortedMap的类型不匹配问题
问题原因
你遇到的类型不匹配错误,核心原因有两个:
Collectors.toMap()的无供应商重载默认返回HashMap,而非SortedMap的实现类;- 若未明确指定泛型参数,编译器可能将结果推导为
Map<Object, Object>,无法直接赋值给SortedMap<String, Integer>。
解决方案
直接在collect()方法中指定返回SortedMap的实现类(比如TreeMap),利用Collectors.toMap()的重载版本,传入创建TreeMap的供应商函数。
正确代码示例
import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; // 假设Book类已定义 public SortedMap<String, Integer> getBookCopyCount() { return booksColl.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, // 提取书名作为键 entry -> entry.getValue().size(), // 提取副本列表的长度作为值 (existingVal, newVal) -> existingVal, // 键冲突时的合并策略(原TreeMap键唯一,此处不会触发) TreeMap::new // 指定返回TreeMap(实现了SortedMap接口) )); }
代码说明
- 键提取:
Map.Entry::getKey直接获取原TreeMap中的书名键; - 值计算:
entry.getValue().size()返回对应书籍副本列表的长度,自动装箱为Integer; - 合并策略:由于原
booksColl是TreeMap,键具有唯一性,这个函数不会被调用,只需传入一个合法的合并逻辑即可; - 返回类型指定:
TreeMap::new作为供应商,让collect()直接生成TreeMap实例,而TreeMap实现了SortedMap接口,可直接赋值给SortedMap<String, Integer>。
备选方案(不推荐)
如果不想在collect()中指定供应商,也可以先收集为普通Map,再转换为SortedMap,但会多一次集合拷贝:
Map<String, Integer> tempMap = booksColl.entrySet() .stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().size() )); SortedMap<String, Integer> bookCountMap = new TreeMap<>(tempMap);
内容的提问来源于stack exchange,提问作者Mattia
相关产品推荐
相关产品推荐

