Stream流简单计算

一、 需求:计算商品的价格

二、代码

class Goods{

    public Goods(String name, Integer num, BigDecimal price) {
        this.name = name;
        this.num = num;
        this.price = price;
    }
    public Goods() {
    }
    /**
     * 商品名称
     */
    private String name;
    /**
     * 数量
     */
    private Integer num;
    /**
     * 单价
     */
    private BigDecimal price;
    /**
     * 该商品总价
     */
    private BigDecimal total;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public BigDecimal getTotal() {
        return total;
    }

    public void setTotal(BigDecimal total) {
        this.total = total;
    }
}

计算

 @Test
    public void test1(){
        Map<String,Object> map = new HashMap<>();
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(new Goods("香蕉",20,BigDecimal.valueOf(2.6)));
        goodsList.add(new Goods("菠萝",10,BigDecimal.valueOf(0.3)));
        goodsList.add(new Goods("可乐",6,BigDecimal.valueOf(2.5)));
        goodsList.add(new Goods("橘子",50,BigDecimal.valueOf(3.6)));
        goodsList.add(new Goods("橙子",5,BigDecimal.valueOf(7.53)));
        goodsList.add(new Goods("苹果",100,BigDecimal.valueOf(3.63)));
        goodsList.add(new Goods("西瓜",20,BigDecimal.valueOf(6.3)));
        goodsList.add(new Goods("葡萄",600,BigDecimal.valueOf(3.6)));
        goodsList.add(new Goods("榴莲",153,BigDecimal.valueOf(2.3)));
        goodsList.stream().forEach(g->g.setTotal(g.getPrice().multiply(BigDecimal.valueOf(g.getNum()))));
        System.out.println(goodsList);
        map.put("goodsList",goodsList);
        map.put("total",goodsList.stream().map(Goods::getTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
        System.out.println(map);
    }

简单计算

三、 完毕

本文为作者原创,转载请申明

你可能感兴趣的:(stream,reduce,计算)