1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| Map<String, String> family = Map.ofEntries(
entry("Teo", "Star Wars"),
entry("Cristina", "James Bond"));
Map<String, String> friends = Map.ofEntries(entry("Raphael", "Star Wars"));
System.out.println("--> Merging the old way, 当键重复时会被覆盖");
Map<String, String> everyone = new HashMap<>(family);
everyone.putAll(friends);
System.out.println(everyone);
// {Cristina=James Bond, Raphael=Star Wars, Teo=Star Wars}
Map<String, String> friends2 = Map.ofEntries(
entry("Raphael", "Star Wars"),
entry("Cristina", "Matrix"));
System.out.println("--> Merging maps using merge(), 可以处理键重复时的情况");
Map<String, String> everyone2 = new HashMap<>(family);
friends2.forEach((k, v) -> everyone2.merge(k, v, (movie1, movie2) -> movie1 + " & " + movie2));
System.out.println(everyone2);
// {Raphael=Star Wars, Cristina=James Bond & Matrix, Teo=Star Wars}
|