jdk8中map新增的merge方法介紹


1.Map.merge方法介紹

  jdk8對於許多常用的類都擴展了一些面向函數,lambda表達式,方法引用的功能,使得java面向函數編程更為方便。其中Map.merge方法就是其中一個,merge方法有三個參數,key:map中的鍵,value:使用者傳入的值,remappingFunction:BiFunction函數接口(該接口接收兩個值,執行自定義功能並返回最終值)。當map中不存在指定的key時,便將傳入的value設置為key的值,當key存在值時,執行一個方法該方法接收key的舊值和傳入的value,執行自定義的方法返回最終結果設置為key的值。

//map.merge方法源碼
default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Objects.requireNonNull(value); V oldValue = get(key); V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value); if(newValue == null) { remove(key); } else { put(key, newValue); } return newValue; }

 比如以下代碼的含義:當name不存在時設置name的值為1,當name的值存在時,將值加1賦給name

public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("name", 1);
        map.merge("name", 1, (oldValue, newValue) -> oldValue + newValue);
        map.merge("count", 1, (oldValue, newValue) -> oldValue + newValue);
        System.out.println(map);
    }
//返回結果
//{count=1, name=2}

2.map.merge()方法使用場景

  merge方法在統計時用的場景比較多,這里舉一個統計學生總成績的例子來說明。現在有一個學生各科成績的集合,要統計每個學生的總成績,以下給出使用merge方法與不使用的寫法

 

public class StudentScoreSum {

    @Data
    static class StudentScore {
        private Integer sid;
        private String scoreName;
        private Integer score;

        public StudentScore(Integer sid, String scoreName, Integer score) {
            this.sid = sid;
            this.scoreName = scoreName;
            this.score = score;
        }

        public StudentScore() {
        }
    }

    public static void main(String[] args) {
        List<StudentScore> list = new ArrayList<>();
        list.add(new StudentScore(1, "chinese", 110));
        list.add(new StudentScore(1, "english", 120));
        list.add(new StudentScore(1, "math", 135));
        list.add(new StudentScore(2, "chinese", 99));
        list.add(new StudentScore(2, "english", 100));
        list.add(new StudentScore(2, "math", 133));
        list.add(new StudentScore(3, "chinese", 88));
        list.add(new StudentScore(3, "english", 140));
        list.add(new StudentScore(3, "math", 90));
        list.add(new StudentScore(4, "chinese", 108));
        list.add(new StudentScore(4, "english", 123));
        list.add(new StudentScore(4, "math", 114));
        list.add(new StudentScore(5, "chinese", 116));
        list.add(new StudentScore(5, "english", 133));
        list.add(new StudentScore(5, "math", 135));

        System.out.println(sum1(list));
        System.out.println(sum2(list));
    }
    //傳統寫法
    public static Map<Integer, Integer> sum1(List<StudentScore> list) {
        Map<Integer, Integer> map = new HashMap<>();
        for (StudentScore studentScore : list) {
            if (map.containsKey(studentScore.getSid())) {
                map.put(studentScore.getSid(),
                        map.get(studentScore.getSid()) + studentScore.getScore());
            } else {
                map.put(studentScore.getSid(), studentScore.getScore());
            }
        }
        return map;
    }

    //merger寫法
    public static Map<Integer, Integer> sum2(List<StudentScore> list) {
        Map<Integer, Integer> map = new HashMap<>();
        list.stream().forEach(studentScore -> map.merge(studentScore.getSid()
                , studentScore.getScore(), Integer::sum));
        return map;
    }
}


//輸出結果

{1=365, 2=332, 3=318, 4=345, 5=384}
{1=365, 2=332, 3=318, 4=345, 5=384}

 

3.總結

  merger方法使用起來確實在一定程度上減少了代碼量,使得代碼更加簡潔。可見,java8新增的函數是編程確實能讓我們少些點模板代碼,更加關注與業務實現。

 

注意:本文僅代表個人理解和看法喲!和本人所在公司和團體無任何關系!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM