我有一个 ConcurrentHashMap<String, Document>
我必须调用一个方法来为每个值删除一个文件。
Document 是一个将文档表示为文件的类。
我在 eclipse 上发现了 forEach 和 forEachValue 方法(有很多签名),但我不知道如何使用它们(有人可以向我解释一下吗?)。
我可以调用 ConcurrentHashMap 方法:
- elements 方法获取
Enumeration<V>
- 获取
Collection<V>
的值方法因此是一个迭代器
哪种解决方案更好?
forEach
方法将 BiConsumer
作为参数,其中消费者的输入是映射中的键值对:
void forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action)
forEachValue
方法将一个Consumer
作为参数,其中消费者的输入仅映射中的值:
void forEachValue(long parallelismThreshold, Consumer<? super V> action)
在每个方法中,您都可以定义来自 documentation 的 parallelismThreshold
状态:
These bulk operations accept a parallelismThreshold argument. Methods proceed sequentially if the current map size is estimated to be less than the given threshold. Using a value of Long.MAX_VALUE suppresses all parallelism.
因此,如果您需要键和值,请使用 forEach
,如果您只需要值,请使用 forEachValue
:
例如
myMap.forEach(Long.MAX_VALUE, (key, document) -> deleteDocument(key, document));
...
public void deleteDocument(String key, Document d) { ... }
或:
myMap.forEachValue(Long.MAX_VALUE, document -> deleteDocument(document));
...
public void deleteDocument(Document d) { ... }