ConcurrentHashMap删除
时间: 2023-10-15 22:31:35 浏览: 127
ConcurrentHashMap可以使用不同的方法来删除元素。一种常见的方法是在遍历时进行修改或删除。可以使用forEach()方法遍历ConcurrentHashMap并在遍历过程中调用remove()方法来删除指定的元素。例如,可以这样写代码来删除键为"name"的元素:
```java
ConcurrentHashMap<String, Object> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("name", "婷婷");
concurrentHashMap.put("sex", "女");
concurrentHashMap.forEach((k, v) -> {
if (k.equals("name")) {
concurrentHashMap.remove("name");
System.out.println("删除成功!");
}
});
concurrentHashMap.forEach((k2, v2) -> {
System.out.println(v2);
});
```
另一种常见的方法是使用迭代器来循环遍历删除元素。可以使用entrySet()方法获取ConcurrentHashMap的键值对集合,并使用迭代器遍历删除指定的元素。例如,可以这样写代码来删除键为"name"的元素:
```java
for (Iterator<Map.Entry<String, Object>> it = concurrentHashMap.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> item = it.next();
String name = item.getKey();
if (name.equals("name")) {
it.remove();
}
}
for (Map.Entry<String, Object> item : concurrentHashMap.entrySet()) {
System.out.println(item.getKey());
}
```
这些方法都可以有效地从ConcurrentHashMap中删除指定的元素。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [并发容器线程安全应对之道-ConcurrentHashMap](https://blog.csdn.net/bxg_kyjgs/article/details/126265405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [HashMap遍历时移除元素](https://blog.csdn.net/Clsrm/article/details/122564673)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文