如何按值是否为Null分组Java HashMap中的Payment键?
解决方案
你可以利用Java Stream的Collectors.partitioningBy来实现这个需求,它专门用于将流分成两个互斥的分组,完美匹配你按值是否为null拆分的场景,而且会保证两个分组都存在(即使某个分组没有元素,也会返回空列表)。
代码实现
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; // 假设已有填充好数据的HashMap HashMap<Payment, String> paymentErrorMap = new HashMap<>(); // 按值是否为null分组,提取对应的Payment键 Map<Boolean, List<Payment>> partitionedPayments = paymentErrorMap.entrySet() .stream() .collect(Collectors.partitioningBy( // 分组判断条件:当前Entry的值是否为null entry -> entry.getValue() == null, // 提取每个Entry的Payment键,收集为List Collectors.mapping(Map.Entry::getKey, Collectors.toList()) )); // 获取两个分组结果 List<Payment> withNullErrors = partitionedPayments.get(true); List<Payment> withErrors = partitionedPayments.get(false);
关于Collectors.groupingBy的备选实现
如果一定要用groupingBy,也能实现,但需要额外处理分组不存在的情况(比如没有值为null的元素时,grouped.get(true)会返回null),示例如下:
Map<Boolean, List<Payment>> groupedPayments = paymentErrorMap.entrySet() .stream() .collect(Collectors.groupingBy( entry -> entry.getValue() == null, Collectors.mapping(Map.Entry::getKey, Collectors.toList()) )); // 用getOrDefault避免空指针 List<Payment> withNullErrors = groupedPayments.getOrDefault(true, List.of()); List<Payment> withErrors = groupedPayments.getOrDefault(false, List.of());
相比之下,partitioningBy更省心,因为它会默认生成两个键为true和false的分组,无需额外处理空值情况。
内容的提问来源于stack exchange,提问作者Ravi
相关产品推荐
相关产品推荐

