Java 8 中的 Map 騷操作输硝,學習下绑谣!

Java 8 最大的特性無異于更多地面向函數(shù)党窜,比如引入了 lambda等拗引,可以更好地進行函數(shù)式編程借宵。

前段時間無意間發(fā)現(xiàn)了 map.merge() 方法,感覺還是很好用的矾削,此文簡單做一些相關(guān)介紹壤玫。首先我們先看一個例子。

merge() 怎么用哼凯?

假設(shè)我們有這么一段業(yè)務邏輯欲间,我有一個學生成績對象的列表,對象包含學生姓名断部、科目猎贴、科目分數(shù)三個屬性,要求求得每個學生的總成績蝴光。

加入列表如下:

private List<StudentScore> buildATestList() {    List<StudentScore> studentScoreList = new ArrayList<>();    StudentScore studentScore1 = new StudentScore() {{        setStuName("張三");        setSubject("語文");        setScore(70);    }};    StudentScore studentScore2 = new StudentScore() {{        setStuName("張三");        setSubject("數(shù)學");        setScore(80);    }};    StudentScore studentScore3 = new StudentScore() {{        setStuName("張三");        setSubject("英語");        setScore(65);    }};    StudentScore studentScore4 = new StudentScore() {{        setStuName("李四");        setSubject("語文");        setScore(68);    }};    StudentScore studentScore5 = new StudentScore() {{        setStuName("李四");        setSubject("數(shù)學");        setScore(70);    }};    StudentScore studentScore6 = new StudentScore() {{        setStuName("李四");        setSubject("英語");        setScore(90);    }};    StudentScore studentScore7 = new StudentScore() {{        setStuName("王五");        setSubject("語文");        setScore(80);    }};    StudentScore studentScore8 = new StudentScore() {{        setStuName("王五");        setSubject("數(shù)學");        setScore(85);    }};    StudentScore studentScore9 = new StudentScore() {{        setStuName("王五");        setSubject("英語");        setScore(70);    }};    studentScoreList.add(studentScore1);    studentScoreList.add(studentScore2);    studentScoreList.add(studentScore3);    studentScoreList.add(studentScore4);    studentScoreList.add(studentScore5);    studentScoreList.add(studentScore6);    studentScoreList.add(studentScore7);    studentScoreList.add(studentScore8);    studentScoreList.add(studentScore9);    return studentScoreList;}

我們先看一下常規(guī)做法:

ObjectMapper objectMapper = new ObjectMapper();List<StudentScore> studentScoreList = buildATestList();Map<String, Integer> studentScoreMap = new HashMap<>();studentScoreList.forEach(studentScore -> {    if (studentScoreMap.containsKey(studentScore.getStuName())) {        studentScoreMap.put(studentScore.getStuName(),                             studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore());    } else {        studentScoreMap.put(studentScore.getStuName(), studentScore.getScore());    }});System.out.println(objectMapper.writeValueAsString(studentScoreMap));// 結(jié)果如下:// {"李四":228,"張三":215,"王五":235}

然后再看一下 merge() 是怎么做的:

Map<String, Integer> studentScoreMap2 = new HashMap<>();studentScoreList.forEach(studentScore -> studentScoreMap2.merge(  studentScore.getStuName(),  studentScore.getScore(),  Integer::sum));System.out.println(objectMapper.writeValueAsString(studentScoreMap2));// 結(jié)果如下:// {"李四":228,"張三":215,"王五":235}

merge() 簡介

merge() 可以這么理解:它將新的值賦值到 key (如果不存在)或更新給定的key 值對應的 value她渴,其源碼如下:

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

我們可以看到原理也是很簡單的,該方法接收三個參數(shù)蔑祟,一個 key 值趁耗,一個 value,一個 remappingFunction 疆虚,如果給定的key不存在苛败,它就變成了 put(key, value) 满葛。

但是,如果 key 已經(jīng)存在一些值罢屈,我們 remappingFunction 可以選擇合并的方式嘀韧,然后將合并得到的 newValue 賦值給原先的 key。

使用場景

這個使用場景相對來說還是比較多的缠捌,比如分組求和這類的操作乳蛾,雖然 stream 中有相關(guān) groupingBy() 方法,但如果你想在循環(huán)中做一些其他操作的時候鄙币,merge() 還是一個挺不錯的選擇的肃叶。

其他

除了 merge() 方法之外,我還看到了一些Java 8 中 map 相關(guān)的其他方法十嘿,比如putIfAbsent 因惭、compute()computeIfAbsent() 绩衷、computeIfPresent蹦魔,這些方法我們看名字應該就知道是什么意思了。

這里我們貼一下 compute()(Map.class) 的源碼咳燕,其返回值是計算后得到的新值:

default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {    Objects.requireNonNull(remappingFunction);    V oldValue = this.get(key);    V newValue = remappingFunction.apply(key, oldValue);    if (newValue == null) {        if (oldValue == null && !this.containsKey(key)) {            return null;        } else {            this.remove(key);            return null;        }    } else {        this.put(key, newValue);        return newValue;    }}

總結(jié)

本文簡單介紹了一下 Map.merge() 的方法勿决,除此之外,Java 8 中的 HashMap 實現(xiàn)方法使用了 TreeNode 和 紅黑樹招盲,在源碼閱讀上可能有一點難度低缩,不過原理上還是相似的,compute() 同理曹货。

所以咆繁,源碼肯定是要看的,不懂的地方多讀多練自然就理解了顶籽。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末玩般,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子礼饱,更是在濱河造成了極大的恐慌坏为,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件镊绪,死亡現(xiàn)場離奇詭異匀伏,居然都是意外死亡,警方通過查閱死者的電腦和手機镰吆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門帘撰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人万皿,你說我怎么就攤上這事摧找『诵校” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵蹬耘,是天一觀的道長芝雪。 經(jīng)常有香客問我,道長综苔,這世上最難降的妖魔是什么惩系? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮如筛,結(jié)果婚禮上堡牡,老公的妹妹穿的比我還像新娘。我一直安慰自己杨刨,他們只是感情好晤柄,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著妖胀,像睡著了一般芥颈。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赚抡,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天爬坑,我揣著相機與錄音,去河邊找鬼涂臣。 笑死盾计,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的肉康。 我是一名探鬼主播闯估,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼灼舍,長吁一口氣:“原來是場噩夢啊……” “哼吼和!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起骑素,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤炫乓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后献丑,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體末捣,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年创橄,在試婚紗的時候發(fā)現(xiàn)自己被綠了箩做。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡妥畏,死狀恐怖邦邦,靈堂內(nèi)的尸體忽然破棺而出安吁,到底是詐尸還是另有隱情,我是刑警寧澤燃辖,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布鬼店,位于F島的核電站,受9級特大地震影響黔龟,放射性物質(zhì)發(fā)生泄漏妇智。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一氏身、第九天 我趴在偏房一處隱蔽的房頂上張望巍棱。 院中可真熱鬧,春花似錦蛋欣、人聲如沸拉盾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽捉偏。三九已至,卻和暖如春泻红,著一層夾襖步出監(jiān)牢的瞬間夭禽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工谊路, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留讹躯,地道東北人。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓缠劝,卻偏偏與公主長得像潮梯,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子惨恭,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355