如何使用Java8 streams过滤Price对象列表获取各productid对应最新价格
实现方案
前置说明
首先假设你定义的Price类已为所有私有属性提供了对应getter方法:getId()、getProductid()、getSequence()、getPrice()。
实现思路
- 按
productid对原始列表分组,将同一产品的所有价格记录归为同一组 - 每组内比较
sequence值,保留该字段最大的记录(即对应产品的最新价格) - 汇总所有分组的保留记录,得到最终结果列表
代码实现
import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; // 原始Price对象列表 List<Price> originalPriceList = ...; // 核心Stream处理逻辑 List<Price> result = originalPriceList.stream() .collect(Collectors.groupingBy( Price::getProductid, // 每组取sequence最大的元素 Collectors.maxBy(Comparator.comparingLong(Price::getSequence)) )) .values() .stream() // 过滤空值(正常场景下分组不为空,该操作为兼容边界情况) .filter(Optional::isPresent) .map(Optional::get) // 如果需要结果按id升序排序可以保留此行,不需要可删除 .sorted(Comparator.comparingLong(Price::getId)) .collect(Collectors.toList());
效果验证
使用你提供的示例数据运行上述代码,最终输出的result列表将仅包含id为3、4的两条记录,完全符合需求。
内容的提问来源于stack exchange,提问作者user2555212
相关产品推荐
相关产品推荐

