JAVA-通过stream流+lumbda表达式精简实现汇总数据并统计。

通过stream流+lumbda表达式精简实现汇总数据并统计。

@Test
public void sumlist() {
//需求:得到两个列表相同交易码和产品的总购买金额和取消金额。
//        通过随机方式仓健两个列表,分别包含n个不同【产品、交易码、购买、取消购买】信息。 
        String prodList ="prodCode:a,b,c";
        String transCodeList = "transCode:t1,t2,t3";
        String transAmtList ="transAmt:10,8,99.9";
        String cancelAmtList = "cancelAmt:1.1,2.22,5";
        List<String> fieldList =Arrays.asList(prodList,transCodeList,transAmtList,cancelAmtlist); List<Map<String, Object>> aList = new ArrayList<>(); List<Map<String, Object>> bList = new ArrayList<>(); for (int i = 0; i < 3; i++) {
        Map<String, Object> map = new HashMap<>(); for (String s : fieldList) {
        map.put(s.split(":")[0].s.split(":")[1].split(",")[RandomUtils.nextInt(3)1); I
        aList.add(map);
        Map<string,Object> map2 = new HashMap<>(); // 必须新建map,否则地址相同,alist会被blist覆盖 for (String s :fieldList){
        map2.put(s.split(":")[0].s.split(":")[1].split(",")[RandomUtils.nextInt(3)]);
        bList.add(map2);
        System.out.println("alist = " + aList); System.out.println("blist = " + bList);//汇总两个列表
        aList.addAll(bList);//分组并统计
        List<Map<String, Object>> sumList = new ArrayList<>(aList.stream().collect(Collectors.toMap(
        po -> po.get("prodCode") + ";" + po.get("transCode"), var -> var,(v1,v2) -> {
        v1.put("transAmt",valueOf(Double.parseDouble(v1.get("transAmt").toString())).add(valueOf(Double.parseDouble(v2.get("transAmt").toString()))));
        v1.put("cancelAmt",valueOf(Double.parseDouble(v1.get("cancelAmt").toString())).add
        NGAJING2
        (valueOf(Double.parseDouble(v2.get("cancelAmt").toString())))); return v1;}))
        .values());
        System.out.println("sumList =" + sumList);
        
        }

打印结果:

sumList=[{prodCode=a,transAmt=99.9,cancelAmt=2.22,transCode=t3}{prodCode=b,transAmt=10, cancelAmt=5,transCode=t2}{prodCode=b,transAmt=10,cancelAmt=1.1,transCode=t1}{prodCode=c, transAmt=28.0,cancelAmt=7.2, transCode=t2}]

你可能感兴趣的:(Java笔记,java,spring)