Skip to content

Commit 869fbff

Browse files
add ConcurrentHashMap example
1 parent 7364584 commit 869fbff

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.examplehub.basics;
2+
3+
import java.util.Map;
4+
import java.util.concurrent.ConcurrentHashMap;
5+
6+
public class ConcurrentHashMapExample {
7+
public static void main(String[] args) {
8+
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
9+
map.put(1, "Java");
10+
map.put(2, "Go");
11+
map.put(3, "Python");
12+
System.out.println(map); /* {1=Java, 2=Go, 3=Python} */
13+
14+
map.putIfAbsent(3, "python");
15+
System.out.println(map); /* {1=Java, 2=Go, 3=Python} */
16+
map.putIfAbsent(4, "HTML");
17+
System.out.println(map); /* {1=Java, 2=Go, 3=Python, 4=HTML} */
18+
19+
map.replace(4, "HTML5");
20+
System.out.println(map); /* {1=Java, 2=Go, 3=Python, 4=HTML5} */
21+
22+
System.out.print("all keys: ");
23+
for (int key : map.keySet()) {
24+
System.out.print(key + " ");
25+
}
26+
System.out.println(); /* all keys: 1 2 3 4 */
27+
28+
/*
29+
key = 1, value = Java
30+
key = 2, value = Go
31+
key = 3, value = Python
32+
key = 4, value = HTML5
33+
*/
34+
for (Map.Entry<Integer, String> entry : map.entrySet()) {
35+
System.out.println(
36+
"key = ".concat(entry.getKey() + "").concat(", value = ").concat(entry.getValue()));
37+
}
38+
39+
40+
41+
System.out.println(map.get(3)); /* Python */
42+
System.out.println(map.getOrDefault(100, "Default value")); /* Default value */
43+
44+
System.out.println(map.remove(3)); /* Python */
45+
System.out.println(map.remove(1, "Java")); /* true */
46+
System.out.println(map); /* {2=Go, 4=HTML5} */
47+
map.clear();
48+
System.out.println(map); /* {} */
49+
}
50+
}

0 commit comments

Comments
 (0)