forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaps1.java
More file actions
48 lines (32 loc) · 1.37 KB
/
Maps1.java
File metadata and controls
48 lines (32 loc) · 1.37 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
package com.winterbe.java8;
import java.util.HashMap;
import java.util.Map;
/**
* @author Benjamin Winterberg
*/
public class Maps1 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
map.computeIfPresent(3, (num, val) -> val + num);
System.out.println(map.get(3)); // val33
map.computeIfPresent(9, (num, val) -> null);
System.out.println(map.containsKey(9)); // false
map.computeIfAbsent(23, num -> "val" + num);
System.out.println(map.containsKey(23)); // true
map.computeIfAbsent(3, num -> "bam");
System.out.println(map.get(3)); // val33
System.out.println(map.getOrDefault(42, "not found")); // not found
map.remove(3, "val3");
System.out.println(map.get(3)); // val33
map.remove(3, "val33");
System.out.println(map.get(3)); // null
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9concat
}
}