3 回答

TA貢獻1868條經(jīng)驗 獲得超4個贊
您可以使用 ,example 輕松迭代map鍵或值for each loop:
Map<String,Document> chm=new ConcurrentHashMap<String,document>();
//this for each loop will iterate over the values of the map
//to iterate over the keys you write: for(String str : chm.keySet())
for(Document doc : chm.values()){
// code to delete the document
// example(if your Document exposes a delete method): doc.delete();
}
正如您在 a 中看到的,for each loop您首先聲明對象的類型:String、int等Document...
第二部分是您的局部變量,例如在上面的情況下,文檔將是Document您的每個變量map,您可以調(diào)用與它相關(guān)的任何方法。
第三部分是the :,你可以把它想象成“in”這個詞
最后一部分是您想要迭代的內(nèi)容,在上面的情況下它是 的map值
Enumeration 和 Iterator 接口的主要區(qū)別在于 Enumeration 只遍歷 Collection 對象,在使用 Enumeration 進行迭代時不能對集合進行任何修改。其中 Iterator 接口允許您在遍歷 Collection 對象時刪除元素(使用該remove()方法)。

TA貢獻1831條經(jīng)驗 獲得超4個贊
該forEach
方法以 aBiConsumer
作為參數(shù),其中消費者的輸入是映射中的鍵和值對:
void?forEach(long?parallelismThreshold,?BiConsumer<??super?K,??super?V>?action)
該forEachValue
方法以 aConsumer
作為參數(shù),其中消費者的輸入只是映射中的值:
void?forEachValue(long?parallelismThreshold,?Consumer<??super?V>?action)
在每種方法中,您可以定義文檔parallelismThreshold
中的說明:
這些批量操作接受parallelismThreshold 參數(shù)。如果估計當(dāng)前地圖大小小于給定閾值,方法將按順序進行。使用 Long.MAX_VALUE 值會抑制所有并行性。
因此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)?{?...?}

TA貢獻1836條經(jīng)驗 獲得超13個贊
如果您需要對 中的每個值執(zhí)行某些操作ConcurrentHashMap
,您有很多選擇:
for (Map.Entry<String, Document> entry : map.entrySet()) {
? ? String key = entry.getKey();
? ? Document doc = entry.getValue();
? ? // code here
}
for (String key : map.keySet()) {
? ? // code here
}
for (Document doc : map.values()) {
? ? // code here
}
map.forEach((key, doc) -> {
? ? // code here
});
map.forEach(1, (key, doc) -> {
? ? // code here will run in parallel
});
map.forEachEntry(1, entry -> {
? ? String key = entry.getKey();
? ? Document doc = entry.getValue();
? ? // code here will run in parallel
});
map.forEachKey(1, key -> {
? ? // code here will run in parallel
});
map.forEachValue(1, doc -> {
? ? // code here will run in parallel
});
上面的示例使用了 lambda 表達式塊,但是如果code here只是一條語句,您可以省略{}大括號和;語句終止符,并將所有內(nèi)容保留在一行中,使其看起來更清晰,例如
map.forEachValue(Long.MAX_VALUE, doc -> DocUtil.deleteFile(doc));
或者使用方法參考:
map.forEachValue(Long.MAX_VALUE, DocUtil::deleteFile);
您更喜歡上述哪一個完全取決于您,部分取決于您是否需要key、doc或兩者,以及是否需要并行處理。
刪除文件時并行處理可能不會提高性能,因為這可能需要磁盤訪問,但如果性能至關(guān)重要,您可以嘗試并行運行并親自看看這是否有幫助。
添加回答
舉報