forked from coderbruis/JavaSourceCodeLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLambdaMapMerge.java
More file actions
58 lines (49 loc) · 1.41 KB
/
LambdaMapMerge.java
File metadata and controls
58 lines (49 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.learnjava.lambda;
import java.util.HashMap;
import java.util.Map;
/**
* 关于Map的合并操作
*
* @author lhy
* @date 2021/7/20
*/
public class LambdaMapMerge {
public static void main(String[] args) {
// mapMerge();
// mapMerge2();
}
/**
* value为int类型的map merge操作,将两个map,相同key merge在一起
*
* key:string
* value:int
*/
public static void mapMerge() {
Map<String, Integer> map1= new HashMap<>();
map1.put("one",1);
map1.put("two",2);
map1.put("three",3);
Map<String,Integer> map2= new HashMap<>();
map2.put("one",1);
map2.put("two",2);
map1.forEach((key, value) -> map2.merge(key, value, Integer::sum));
System.out.println(map2);
}
/**
* value为int类型的map merge操作,将两个map,相同key merge在一起
*
* key:string
* value:String
*/
public static void mapMerge2() {
Map<String,String> map1= new HashMap<>();
map1.put("one","1");
map1.put("two","2");
map1.put("three","3");
Map<String,String> map2= new HashMap<>();
map2.put("one","1");
map2.put("two","2");
map1.forEach((key, value) -> map2.merge(key, value,(total, num) -> String.valueOf(Integer.parseInt(total) + Integer.parseInt(num))));
System.out.println(map2);
}
}