Java 8 最大的特性無異於更多地面向函數,好比引入了 lambda
等,能夠更好地進行函數式編程。前段時間無心間發現了 map.merge()
方法,感受仍是很好用的,此文簡單作一些相關介紹。首先咱們先看一個例子。java
merge()
怎麼用?假設咱們有這麼一段業務邏輯,我有一個學生成績對象的列表,對象包含學生姓名、科目、科目分數三個屬性,要求求得每一個學生的總成績。加入列表以下:git
private List<StudentScore> buildATestList() {
List<StudentScore> studentScoreList = new ArrayList<>();
StudentScore studentScore1 = new StudentScore() {{
setStuName("張三");
setSubject("語文");
setScore(70);
}};
StudentScore studentScore2 = new StudentScore() {{
setStuName("張三");
setSubject("數學");
setScore(80);
}};
StudentScore studentScore3 = new StudentScore() {{
setStuName("張三");
setSubject("英語");
setScore(65);
}};
StudentScore studentScore4 = new StudentScore() {{
setStuName("李四");
setSubject("語文");
setScore(68);
}};
StudentScore studentScore5 = new StudentScore() {{
setStuName("李四");
setSubject("數學");
setScore(70);
}};
StudentScore studentScore6 = new StudentScore() {{
setStuName("李四");
setSubject("英語");
setScore(90);
}};
StudentScore studentScore7 = new StudentScore() {{
setStuName("王五");
setSubject("語文");
setScore(80);
}};
StudentScore studentScore8 = new StudentScore() {{
setStuName("王五");
setSubject("數學");
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;
}
複製代碼
咱們先看一下常規作法:github
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));
// 結果以下:
// {"李四":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));
// 結果以下:
// {"李四":228,"張三":215,"王五":235}
複製代碼
merge()
簡介merge()
能夠這麼理解:它將新的值賦值到 key (若是不存在)或更新給定的key 值對應的 value,其源碼以下:app
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;
}
複製代碼
咱們能夠看到原理也是很簡單的,該方法接收三個參數,一個 key 值,一個 value,一個 remappingFunction
,若是給定的key不存在,它就變成了 put(key, value)
。可是,若是 key 已經存在一些值,咱們 remappingFunction
能夠選擇合併的方式,而後將合併獲得的 newValue
賦值給原先的 key。函數式編程
這個使用場景相對來講仍是比較多的,好比分組求和這類的操做,雖然 stream 中有相關 groupingBy()
方法,但若是你想在循環中作一些其餘操做的時候,merge()
仍是一個挺不錯的選擇的。函數
除了 merge()
方法以外,我還看到了一些Java 8 中 map
相關的其餘方法,好比 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;
}
}
複製代碼
本文簡單介紹了一下 Map.merge()
的方法,除此以外,Java 8 中的 HashMap
實現方法使用了 TreeNode
和 紅黑樹,在源碼閱讀上可能有一點難度,不過原理上仍是類似的,compute()
同理。因此,源碼確定是要看的,不懂的地方多讀多練天然就理解了。ui
參考:this
測試代碼地址: