Java 8 中 Map 騷操作之 merge() 的使用方法
Java 8 最大的特性無(wú)異于更多地面向函數(shù),比如引入了lambda等,可以更好地進(jìn)行函數(shù)式編程。前段時(shí)間無(wú)意間發(fā)現(xiàn)了map.merge()方法,感覺(jué)還是很好用的,此文簡(jiǎn)單做一些相關(guān)介紹。首先我們先看一個(gè)例子。
merge()怎么用?
假設(shè)我們有這么一段業(yè)務(wù)邏輯,我有一個(gè)學(xué)生成績(jī)對(duì)象的列表,對(duì)象包含學(xué)生姓名、科目、科目分?jǐn)?shù)三個(gè)屬性,要求求得每個(gè)學(xué)生的總成績(jī)。加入列表如下:
private List<StudentScore> buildATestList() {
List<StudentScore> studentScoreList = new ArrayList<>();
StudentScore studentScore1 = new StudentScore() {{
setStuName("張三");
setSubject("語(yǔ)文");
setScore(70);
}};
StudentScore studentScore2 = new StudentScore() {{
setStuName("張三");
setSubject("數(shù)學(xué)");
setScore(80);
}};
StudentScore studentScore3 = new StudentScore() {{
setStuName("張三");
setSubject("英語(yǔ)");
setScore(65);
}};
StudentScore studentScore4 = new StudentScore() {{
setStuName("李四");
setSubject("語(yǔ)文");
setScore(68);
}};
StudentScore studentScore5 = new StudentScore() {{
setStuName("李四");
setSubject("數(shù)學(xué)");
setScore(70);
}};
StudentScore studentScore6 = new StudentScore() {{
setStuName("李四");
setSubject("英語(yǔ)");
setScore(90);
}};
StudentScore studentScore7 = new StudentScore() {{
setStuName("王五");
setSubject("語(yǔ)文");
setScore(80);
}};
StudentScore studentScore8 = new StudentScore() {{
setStuName("王五");
setSubject("數(shù)學(xué)");
setScore(85);
}};
StudentScore studentScore9 = new StudentScore() {{
setStuName("王五");
setSubject("英語(yǔ)");
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()簡(jiǎn)介
merge()可以這么理解:它將新的值賦值到 key (如果不存在)或更新給定的key 值對(duì)應(yīng)的 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;
}
我們可以看到原理也是很簡(jiǎn)單的,該方法接收三個(gè)參數(shù),一個(gè) key 值,一個(gè) value,一個(gè)remappingFunction,如果給定的key不存在,它就變成了put(key, value)。但是,如果 key 已經(jīng)存在一些值,我們r(jià)emappingFunction可以選擇合并的方式,然后將合并得到的newValue賦值給原先的 key。
使用場(chǎng)景
這個(gè)使用場(chǎng)景相對(duì)來(lái)說(shuō)還是比較多的,比如分組求和這類的操作,雖然 stream 中有相關(guān)groupingBy()方法,但如果你想在循環(huán)中做一些其他操作的時(shí)候,merge()還是一個(gè)挺不錯(cuò)的選擇的。
其他
除了merge()方法之外,我還看到了一些Java 8 中map相關(guān)的其他方法,比如putIfAbsent、compute()、computeIfAbsent()、computeIfPresent,這些方法我們看名字應(yīng)該就知道是什么意思了,故此處就不做過(guò)多介紹了,感興趣的可以簡(jiǎn)單閱讀一下源碼(都還是挺易懂的),這里我們貼一下compute()(Map.class)的源碼,其返回值是計(jì)算后得到的新值:
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é)
本文簡(jiǎn)單介紹了一下Map.merge()的方法,除此之外,Java 8 中的HashMap實(shí)現(xiàn)方法使用了TreeNode和 紅黑樹(shù),在源碼閱讀上可能有一點(diǎn)難度,不過(guò)原理上還是相似的,compute()同理。所以,源碼肯定是要看的,不懂的地方多讀多練自然就理解了。
鏈接
參考:
測(cè)試代碼地址:
到此這篇關(guān)于Java 8 中 Map 騷操作之 merge() 的用法 的文章就介紹到這了,更多相關(guān)Java 8 merge()用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java使用Socket類接收和發(fā)送數(shù)據(jù)
Socket類是負(fù)責(zé)處理客戶端通信的Java類。本文主要是介紹java使用Socket類接收和發(fā)送數(shù)據(jù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-10-10
解決RestTemplate第一次請(qǐng)求響應(yīng)速度較慢的問(wèn)題
這篇文章主要介紹了解決RestTemplate第一次請(qǐng)求響應(yīng)速度較慢的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
Java讀取網(wǎng)絡(luò)文件的實(shí)例代碼
這篇文章主要介紹了Java讀取網(wǎng)絡(luò)文件的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
mybatis collection關(guān)聯(lián)查詢多個(gè)參數(shù)方式
在使用MyBatis進(jìn)行關(guān)聯(lián)查詢時(shí),往往需要根據(jù)多個(gè)參數(shù)進(jìn)行查詢,例如,使用evtId和businessType作為查詢條件,同時(shí)在resultMap中配置id和businessType1作為結(jié)果映射,這種情況下,可以通過(guò)<sql>標(biāo)簽定義參數(shù)模板,或者使用@Param注解指定參數(shù)名稱2024-10-10
Java將數(shù)字金額轉(zhuǎn)為大寫(xiě)中文金額
這篇文章主要為大家詳細(xì)介紹了Java將數(shù)字金額轉(zhuǎn)為大寫(xiě)中文金額,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-08-08
java實(shí)現(xiàn)雙色球機(jī)選號(hào)碼生成器
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)雙色球機(jī)選號(hào)碼生成器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01
SpringBoot啟動(dòng)時(shí)如何修改上下文
本文介紹了如何在Spring Boot啟動(dòng)時(shí)修改上下文,以便加載封裝JAR中的國(guó)際化文件,通過(guò)在resources目錄下的META-INF文件夾中的spring.factories文件中配置指定類,可以實(shí)現(xiàn)這一功能2024-11-11
Spring項(xiàng)目中swagger用法與swagger-ui使用
這篇文章主要介紹了Spring項(xiàng)目中swagger用法與swagger-ui使用,通過(guò)圖文并茂的形式給大家介紹了編寫(xiě)springboot項(xiàng)目的方法及導(dǎo)入spring-fox依賴的代碼詳解,需要的朋友可以參考下2021-05-05

