ConcurrentHashMap的四种写法
时间: 2023-10-27 16:37:46 浏览: 43
1. 使用ConcurrentHashMap类的put()方法添加元素:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
2. 使用ConcurrentHashMap类的putIfAbsent()方法添加元素,如果key已存在,则返回其对应的value,如果不存在,则添加key-value键值对并返回null:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
Integer value1 = map.putIfAbsent("key1", 1);
Integer value2 = map.putIfAbsent("key2", 2);
Integer value3 = map.putIfAbsent("key3", 3);
3. 使用ConcurrentHashMap类的compute()方法对指定key的value进行更新或计算:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.compute("key1", (k, v) -> v + 1);
4. 使用ConcurrentHashMap类的merge()方法合并两个ConcurrentHashMap:
ConcurrentHashMap<String, Integer> map1 = new ConcurrentHashMap<>();
map1.put("key1", 1);
map1.put("key2", 2);
ConcurrentHashMap<String, Integer> map2 = new ConcurrentHashMap<>();
map2.put("key1", 3);
map2.put("key3", 4);
map2.forEach((k, v) -> map1.merge(k, v, (v1, v2) -> v1 + v2));