Java中Collectors.groupingBy方法内Lambda函数报错求助
问题排查与修复
错误原因
你代码里的报错是因为错误地把Map.Entry的getter方法当成字段访问了。Java中Map.Entry的键和值是通过getKey()和getValue()方法获取的,不是直接访问key或value字段。你写的e.getKey、e.getValue.intValue()都是语法错误,必须改成方法调用形式。
另外,你方法声明返回的是SortedMap,但原代码返回null,最后也需要修正返回逻辑,确保返回符合要求的有序Map实例。
修正后的完整代码
public SortedMap<Integer, List<String>> slotsPerNofParticipants(String gymnname) throws FitException{ // 原Map:键=时段字符串,值=对应时段的参与人数 Map<String, Long> map = this.reservationsColl.stream() .filter(r -> r.getGym().getName().equals(gymnname)) .collect(Collectors.groupingBy( r -> r.getDayslotStringFormat(), Collectors.counting() )); // 反转后的Map:键=参与人数,值=对应时段的列表,同时用TreeMap实现SortedMap SortedMap<Integer, List<String>> res = map.entrySet().stream() .collect(Collectors.groupingBy( e -> e.getValue().intValue(), // 修正:调用getValue()方法获取人数 TreeMap::new, // 指定用TreeMap实现有序Map Collectors.mapping(e -> e.getKey(), Collectors.toList()) // 修正:调用getKey()方法获取时段 )); return res; // 返回正确的SortedMap实例 }
关键修正点
- 将
e.getValue.intValue()改为e.getValue().intValue():调用getValue()获取Long类型的人数,再转为Integer - 将
e.getKey改为e.getKey():调用getKey()获取时段字符串 - 在
groupingBy中添加TreeMap::new作为第二个参数,确保返回的Map是SortedMap的实现类(TreeMap),匹配方法返回值类型 - 把返回
null改成返回修正后的res对象
内容的提问来源于stack exchange,提问作者Mattia
相关产品推荐
相关产品推荐

