map的merge和computeIfAbsent来简化你的代码

格言:在程序猿界混出点名堂!

JAVA8在map新增了方法merge和computeIfAbsent,直接通过例子来看一下如何使用?

1.merge

需求场景:有一个学生的集合,按班级统计学生的成绩总和。
a.老的写法

public static Map mergeOld() {
        List students = Lists.newArrayList();
        students.add(new Student("张三", "一年级一班", 70));
        students.add(new Student("李四", "一年级一班", 70));
        students.add(new Student("王五", "一年级二班", 80));
        Map map = new HashMap();

        students.forEach(s -> {
            String clazz = s.getClazz();
            Integer score = s.getScore();
            Integer summary;
            if ((summary = map.get(clazz)) != null) {
                map.put(clazz, summary + score);
            } else {
                map.put(clazz, score);
            }
        });
        return map;
    }

b.新的写法

public static Map mergeNew() {
        List students = Lists.newArrayList();
        students.add(new Student("张三", "一年级一班", 70));
        students.add(new Student("李四", "一年级一班", 70));
        students.add(new Student("王五", "一年级二班", 80));
        Map map = new HashMap();

        students.forEach(s -> map.merge(s.getClazz(), s.getScore(), (ov, nv) -> ov + nv));
        return map;
    }

merge是对同一个key的新value和旧value的一个合并,合并规则自己实现,
该方法第一个参数当然为key,第二个参数是新value,第三个参数是计算规则。
如果key对应的旧value为空,则value是新value,如果key对应的就value不为空,则value为计算的value。
一句话实现以上逻辑是不是很简单。。

2.computeIfAbsent

需求场景:有一个学生的集合,按班级统计学生的成绩的分布。
a.老的写法

public static Map> computeIfAbsentOld() {
        List students = Lists.newArrayList();
        students.add(new Student("张三", "一年级一班", 70));
        students.add(new Student("李四", "一年级一班", 70));
        students.add(new Student("王五", "一年级二班", 80));
        Map> map = new HashMap>();
        students.forEach(s -> {
            String clazz = s.getClazz();
            Integer score = s.getScore();
            List scores;
            if ((scores = map.get(clazz)) == null) {
                map.put(clazz, Lists.newArrayList(score));
            } else {
                scores.add(score);
            }
        });
        return map;
    }

b.新的写法

public static Map> computeIfAbsentNew() {
        List students = Lists.newArrayList();
        students.add(new Student("张三", "一年级一班", 70));
        students.add(new Student("李四", "一年级一班", 70));
        students.add(new Student("王五", "一年级二班", 80));
        Map> map = new HashMap>();
        
        
        students.forEach(s -> map.computeIfAbsent(s.getClazz(), (k)->Lists.newArrayList()).add(s.getScore()));
        return map;
    }

computeIfAbsent第一个参数为key,第二个参数为value
当key对应的value为空时,才设置value
关键在于返回值如果key对应的value为空,则返回新put的value,如果key对应的value不为空,则返回旧value

赶快试试吧!

你可能感兴趣的:(map的merge和computeIfAbsent来简化你的代码)