Java中如何将Booking列表按OfficeType分组统计数量到Map对象
按OfficeType分组统计Booking数量的Stream实现
你可以通过Java Stream的collect方法结合Collectors工具类实现分组统计,以下是两种常用方案:
方案一:groupingBy + counting + 类型转换
Map<OfficeType, Integer> officeTypeMap = bookingList.stream() .collect(Collectors.groupingBy( Booking::getOfficeType, // 分组依据:Booking的officeType字段 Collectors.collectingAndThen(Collectors.counting(), Long::intValue) // 统计数量并转为Integer ));
Collectors.counting()返回Long类型的统计结果,通过collectingAndThen可以将其转换为Integer,匹配你需要的Map值类型。
方案二:groupingBy + summingInt(更简洁)
Map<OfficeType, Integer> officeTypeMap = bookingList.stream() .collect(Collectors.groupingBy( Booking::getOfficeType, Collectors.summingInt(e -> 1) // 每个元素计数为1,直接累加得到Integer ));
这种方式直接通过summingInt累加每个元素的计数(固定为1),最终直接得到Integer类型的统计值,代码更简洁直观。
可选:过滤null值
如果存在officeType为null的Booking,会被分到key为null的分组中。若需要排除这类数据,可以在Stream中添加过滤操作:
Map<OfficeType, Integer> officeTypeMap = bookingList.stream() .filter(booking -> booking.getOfficeType() != null) // 过滤掉officeType为null的记录 .collect(Collectors.groupingBy( Booking::getOfficeType, Collectors.summingInt(e -> 1) ));
内容的提问来源于stack exchange,提问作者abidinberkay
相关产品推荐
相关产品推荐

