工作中在處理集合的時候會經常遇到需要分組然后計算某屬性的和,在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);
});
}
運行結果
小結
工作記錄。