Java Stream按offeringClass和paymentOption双字段分组报错问题求助
错误原因排查
- API用法错误:
Stream.collect()方法的入参要求是收集器实例,你直接把字符串拼接表达式作为collect的第一个参数,完全不符合Java Stream API规范,编译阶段就会报错。 - Key类型不匹配:你声明的接收变量是
Map<String, List<ServerPricing>>,但代码里groupingBy返回的key是Arrays.asList()生成的List类型,类型不兼容会直接抛出类型转换异常。 - 潜在空指针风险:如果
offeringClass或paymentOption字段为null,调用其getter方法会直接抛出空指针异常。
修正后的代码
如果你要使用字符串作为分组key,推荐增加分隔符避免不同字段拼接后意外重复,正确写法如下:
Map<String, List<ServerPricing>> groupByOfferingClassPaymentOption = serverPricingList.stream() // 不需要过滤空值可以删掉这行 .filter(p -> p.getOfferingClass() != null && p.getPaymentOption() != null) .collect(Collectors.groupingBy( p -> p.getOfferingClass().getOfferingClassMapped() + "_" + p.getPaymentOption().getPaymentOptionMapped() ));
如果你希望用组合对象作为key避免字符串拼接的问题,可以用List作为key,对应修改接收变量类型即可:
Map<List<String>, List<ServerPricing>> groupByOfferingClassPaymentOption = serverPricingList.stream() .filter(p -> p.getOfferingClass() != null && p.getPaymentOption() != null) .collect(Collectors.groupingBy( p -> Arrays.asList(p.getOfferingClass().getOfferingClassMapped(), p.getPaymentOption().getPaymentOptionMapped()) ));
内容的提问来源于stack exchange,提问作者upog
相关产品推荐
相关产品推荐

