工作中在处理集合的时候会经常遇到需要分组然后计算某属性的和,在java8中,通过stream来操作集合,还是非常方便的,像过滤(filter)、分组(group)、获取单个属性的值,总而言之,简单方便。也有人不推荐使用,觉得写的太多,可读性会变差,主要看个人喜好吧。
下面主要是处理分组求和的代码
一个商品实体类,添加一些计算属性
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
/**
* @Auther: John.ma
* @Description: 商品类型
* @Date: 2019/5/17 13:51
*/
@Setter
@Getter
@ToString
@Accessors(chain = true)
public class Goods {
/** 商品类型 */
@ApiModelProperty(value = "商品类型")
private String goodsType;
/** 备件名称 */
@ApiModelProperty(value = "备件名称")
private String goodsName;
/** 供应商 */
@ApiModelProperty(value = "供应商")
private String supplier;
/** 一个月预测 */
@ApiModelProperty(value = "一个月预测")
private Integer oneMonthCount;
/** 三个月预测 */
@ApiModelProperty(value = "三个月预测")
private Integer threeMonthCount;
/** 半年预测 */
@ApiModelProperty(value = "半年预测")
private Integer sixMonthCount;
@ApiModelProperty(value = "数量")
private Integer count;
}
一个测试方法
public static void group() {
List<Goods> stockGoodsVOS = Lists.newArrayList();
Goods vo = new Goods();
Goods vo1 = new Goods();
Goods vo2 = new Goods();
Goods vo3 = new Goods();
vo.setGoodsType("a").setGoodsName("test").setSupplier("a").setOneMonthCount(10)
.setThreeMonthCount(20).setSixMonthCount(15).setCount(5);
vo1.setGoodsType("b").setGoodsName("testa").setSupplier("b").setOneMonthCount(5)
.setThreeMonthCount(5).setSixMonthCount(5).setCount(5);
vo2.setGoodsType("c").setGoodsName("testa").setSupplier("b").setOneMonthCount(1)
.setThreeMonthCount(1).setSixMonthCount(1).setCount(1);
vo3.setGoodsType("c").setGoodsName("testa").setSupplier("b").setOneMonthCount(1)
.setThreeMonthCount(1).setSixMonthCount(1).setCount(1);
stockGoodsVOS.add(vo);
stockGoodsVOS.add(vo1);
stockGoodsVOS.add(vo2);
stockGoodsVOS.add(vo3);
List<Goods> goodsVOS = Lists.newArrayList();
//主要代码
stockGoodsVOS.stream()
.collect(Collectors.groupingBy(Goods::getGoodsType))
.forEach((k, v) -> {
Optional<Goods> reduce = v.stream().reduce((v1, v2) -> {
v1.setOneMonthCount(BigDecimal.valueOf(v1.getOneMonthCount())
.add(BigDecimal.valueOf(v2.getOneMonthCount())).intValue());
v1.setThreeMonthCount(BigDecimal.valueOf(v1.getThreeMonthCount())
.add(BigDecimal.valueOf(v2.getThreeMonthCount())).intValue());
v1.setSixMonthCount(BigDecimal.valueOf(v1.getSixMonthCount())
.add(BigDecimal.valueOf(v2.getSixMonthCount())).intValue());
return v1;
});
goodsVOS.add(reduce.get());
});
goodsVOS.forEach(vos -> {
System.out.println(vos);
});
}
运行结果
小结
工作记录。