gpt4 book ai didi

java - ConcurrentHashMap中的forEach和forEachEntry有什么区别

转载 作者:搜寻专家 更新时间:2023-11-01 01:40:46 24 4
gpt4 key购买 nike

在 Java 8 ConcurrentHashMap 中引入了两个新方法,即。 forEachforEachEntry .

仔细观察它们两个具有基本相同的参数 - forEach 具有通过 BiConsumer 提供的键和值,而 forEachEntry 具有 Map .Entry 通过 Consumer 提供,从中可以派生键和值。

打印所有 map 条目的简单用例可以由它们中的任何一个实现,如下所示

ConcurrentHashMap<String, Integer> map = Stream.of("One", "Two", "Three", "Four", "Five").
collect(Collectors.toConcurrentMap( str -> str,
str -> str.length(),
(str, len) -> len,
ConcurrentHashMap::new));

map.forEach(1, (k, v) -> System.out.println(k + " " + v));

map.forEachEntry(1, entry -> System.out.println(entry.getKey() + " " + entry.getValue()));

此外,根据文档,Map.Entry.setValue 不支持批量操作;所以使用 Map.Entry 而不是普通键值的好处似乎被打败了。

.... that may transiently change while computation is in progress; and except for forEach actions, should ideally be side-effect-free. Bulk operations on Map.Entry objects do not support method setValue.

因此 IMO 两种方法可以互换使用(除非我遗漏了一些非常明显的东西)

所以我的问题是

  • 为什么引入了两种签名基本相同的方法
  • 如果有什么不同,那是什么
  • 一种方法比另一种方法有什么好处(解释它们的简单用例就足够了)

最佳答案

唯一的区别是一个接受 BiConsumer 而另一个只接受一个 Consumer。

这里是相关代码:

// forEach
static final class ForEachMappingTask<K,V>
extends BulkTask<K,V,Void> {
final BiConsumer<? super K, ? super V> action;
ForEachMappingTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
BiConsumer<? super K,? super V> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final BiConsumer<? super K, ? super V> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachMappingTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.accept(p.key, p.val);
propagateCompletion();
}
}
}

// forEachEntry
static final class ForEachEntryTask<K,V>
extends BulkTask<K,V,Void> {
final Consumer<? super Entry<K,V>> action;
ForEachEntryTask
(BulkTask<K,V,?> p, int b, int i, int f, Node<K,V>[] t,
Consumer<? super Entry<K,V>> action) {
super(p, b, i, f, t);
this.action = action;
}
public final void compute() {
final Consumer<? super Entry<K,V>> action;
if ((action = this.action) != null) {
for (int i = baseIndex, f, h; batch > 0 &&
(h = ((f = baseLimit) + i) >>> 1) > i;) {
addToPendingCount(1);
new ForEachEntryTask<K,V>
(this, batch >>>= 1, baseLimit = h, f, tab,
action).fork();
}
for (Node<K,V> p; (p = advance()) != null; )
action.accept(p);
propagateCompletion();
}
}
}

有点像设置组件大小的两种方法:setSize(Dimension)setSize(int, int)

关于java - ConcurrentHashMap中的forEach和forEachEntry有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42810289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com