Map的merge()用法

1、java8 Map的新用法

 Job job = new Job("李四","语文",98);
        Job job1 = new Job("李四","数学",85);
        Job job2 = new Job("王五","语文",90);
        Job job3 = new Job("王五","数学",84);
        Job job4 = new Job("赵三","语文",89);
        Job job5 = new Job("赵三","数学",82);
        List<Job> list = new ArrayList<>();
        list.add(job);
        list.add(job1);
        list.add(job2);
        list.add(job3);
        list.add(job4);
        list.add(job5);
        Map<String,Integer>  treeMap = new HashMap<>();
        list.forEach( jobs -> {
            treeMap.merge(jobs.getName(),jobs.getScore(),Integer::sum);
        });
        System.out.println("触发信息内容:"+ com.alibaba.fastjson.JSON.toJSONString(treeMap));

结果:

触发信息内容:{"李四":183,"赵三":171,"王五":174}

 结论:可以较好的处理统计

posted @ 2020-11-04 10:26  活出自己范儿  Views(1374)  Comments(0Edit  收藏  举报