count属性JAVA_java按某属性分组并计算相关属性的和。

工作中在处理集合的时候会经常遇到需要分组然后计算某属性的和,在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 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 goodsVOS = Lists.newArrayList();

//主要代码

stockGoodsVOS.stream()

.collect(Collectors.groupingBy(Goods::getGoodsType))

.forEach((k, v) -> {

Optional 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);

});

}

运行结果

2c74c96077d6415fae189c9d0ee06156.png

小结

工作记录。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值