Java ConcurrentHashMap: entrySet()方法示例

x33g5p2x  于2022-09-25 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(221)

在本文中,我们将学习 Java ConcurrentHashMap 类的 entrySet() 方法。 ConcurrentHashMap 是一个哈希表,它支持检索的完全并发和更新的高预期并发。 entrySet()ConcurrentHashMap 的方法,带有以下 Java 文档。

Set<Map.Entry<K,V>> entrySet()

1.entrySet() 方法返回此 ConcurrentHashMap 中包含的地图的 Set 视图。
2. 如果此 ConcurrentHashMap 更改,则 Set 视图也会更改,如果此 Set 更改,则 ConcurrentHashMap 也会更改。
3. 如果我们从这个 Set 中删除元素,那么相应的映射也会从映射中删除。

entrySet()

在这里,我们将创建一个 ConcurrentHashMap 并放置一些内容。然后我们在它上面调用 entrySet() 方法。使用 for 循环,我们迭代集合。

ConcurrentHashMap<String, Integer> conMap = new ConcurrentHashMap<>();
conMap.put("Mahesh", 22);
conMap.put("Nilesh", 25);
conMap.put("Krishn", 20);
conMap.put("Pradeep", 23);

Set<Entry<String, Integer>> entrySet = conMap.entrySet();
for (Map.Entry<String, Integer> mapEntry : entrySet) {
  System.out.println(mapEntry.getKey() + " " + mapEntry.getValue());
}

输出

Krishn 20
Mahesh 22
Pradeep 23
Nilesh 25

删除元素

可以使用 Iterator.removeSet.removeSet.removeIf 方法删除该元素。
Set 视图中的更改也会执行 ConcurrentHashMap 中的相应更改。
现在找到删除元素的方法。
1。使用 Iterator.remove

Iterator<Map.Entry<String, Integer>> iterator = conMap.entrySet().iterator();
while (iterator.hasNext()) {
  Entry<String, Integer> entry = iterator.next();
  if (entry.getValue() == 20) {
	iterator.remove();
  }
}
System.out.println(conMap);

输出

{Mahesh=22, Pradeep=23, Nilesh=25}

2。使用 Set.remove

Set<Entry<String, Integer>> entrySet = conMap.entrySet();
for (Map.Entry<String, Integer> mapEntry : entrySet) {
  if (mapEntry.getKey().equals("Nilesh")) {
	entrySet.remove(mapEntry);
  }
}
System.out.println(conMap);

输出

{Krishn=20, Mahesh=22, Pradeep=23}

3。使用 Set.remove

Set<Entry<String, Integer>> entrySet = conMap.entrySet();
entrySet.removeIf(e -> e.getKey().equals("Krishn"));
System.out.println(conMap);

输出

{Mahesh=22, Pradeep=23, Nilesh=25}

相关文章

微信公众号

最新文章

更多