java List的stream().collect()方法实战

文章目录

  • 订单类
  • 测试类
  • 测试结果

这几天在做银联的银行卡对账时,一开始只使用参考号来确定一笔交易,但是这样是不严谨的,项目经理要求使用商户号、终端号、流水号、批次号、参考号五个数据项来确定唯一性,所以本次list转map是在此背景下产生的。

订单类

public class Order {
    /**商户号**/
    private String shh;
    /**终端号**/
    private String zdh;
    /**流水号**/
    private String lsh;
    /**批次号**/
    private String pch;
    /**参考号**/
    private String ckh;
    /**订单金额**/
    private BigDecimal amount;

    public Order(String shh, String zdh, String lsh, String pch, String ckh, BigDecimal amount) {
        this.shh = shh;
        this.zdh = zdh;
        this.lsh = lsh;
        this.pch = pch;
        this.ckh = ckh;
        this.amount = amount;
    }

    public String getShh() {
        return shh;
    }

    public void setShh(String shh) {
        this.shh = shh;
    }

    public String getZdh() {
        return zdh;
    }

    public void setZdh(String zdh) {
        this.zdh = zdh;
    }

    public String getLsh() {
        return lsh;
    }

    public void setLsh(String lsh) {
        this.lsh = lsh;
    }

    public String getPch() {
        return pch;
    }

    public void setPch(String pch) {
        this.pch = pch;
    }

    public String getCkh() {
        return ckh;
    }

    public void setCkh(String ckh) {
        this.ckh = ckh;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }

    /**
     * 商户号+终端号+流水号+批次号+参考号
     * @return
     */
    public String getMapKey(){
        return getShh()+getZdh()+getLsh()+getPch()+getCkh();
    }
}

重点是定义一个getMapKey()方法,此方法用来生成key

测试类

public class OrderMapTest {
    public static void main(String[] args) {
        Order a = new Order("s1","z1","01","0001","202307210923",new BigDecimal("0.01"));
        Order b = new Order("s2","z2","01","0001","202307210924",new BigDecimal("0.02"));
        Order c = new Order("s3","z3","01","0001","202307210925",new BigDecimal("0.03"));
        Order d = new Order("s4","z4","01","0001","202307210926",new BigDecimal("0.04"));
        Order e = new Order("s5","z5","01","0001","202307210927",new BigDecimal("0.05"));

        List<Order> orders = new ArrayList<Order>();
        orders.add(a);
        orders.add(b);
        orders.add(c);
        orders.add(d);
        orders.add(e);

		// list转换成map,使用getMapKey自定义的方法生成key,Order对象做value
        Map<String, Order> map = orders.stream().collect(Collectors.toMap(Order::getMapKey, order -> order));

        Set<String> keys = map.keySet();

        System.out.println("keys====" + keys);

        for (String key : keys) {

            System.out.println(key + ": " + map.get(key).getAmount());

        }
    }
}

测试结果

在这里插入图片描述

你可能感兴趣的:(JAVA,java,list,stream)