Java中遍歷ConcurrentHashMap的四種方式詳解
這篇文章主要介紹了Java中遍歷ConcurrentHashMap的四種方式詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
方式一:在for-each循環(huán)中使用entries來遍歷
System.out.println("方式一:在for-each循環(huán)中使用entries來遍歷");
for (Map.Entry<String, String> entry: map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
方法二:在for-each循環(huán)中遍歷keys或values,這種方式適用于需要值或者鍵的情況,方法二比方法一快了10%
System.out.println("方法二:在for-each循環(huán)中遍歷keys或values,這種方式適用于需要值或者鍵的情況");
//遍歷鍵
for (String key : map.keySet()) {
System.out.println("key = " + key);
}
//遍歷值
for (String value : map.values()) {
System.out.println("value = " + value);
}
方法三:使用Iterator遍歷,使用并發(fā)集合不會報異常,性能類似于方法二
//使用泛型 Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator(); System.out.println("使用Iterator遍歷,并且使用泛型:"); while (entries.hasNext()) { Map.Entry<String, String> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); //注意這里操作了集合,下面的的遍歷不會再打印0 if("0".equals(entry.getKey())) { map.remove(entry.getKey()); } } //不使用泛型 Iterator entrys = map.entrySet().iterator(); System.out.println("使用Iterator遍歷,并且不使用泛型"); while (entrys.hasNext()) { Map.Entry entry = (Map.Entry) entrys.next(); String key = (String)entry.getKey(); String value = (String)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); }
方式四:通過鍵找值遍歷,該方法效率相當?shù)?不建議使用
System.out.println("方式四:通過鍵找值遍歷"); for (String key : map.keySet()) { String value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用profiles進行多環(huán)境配置的代碼實現(xiàn)
在項目開發(fā)的過程中會用到多個環(huán)境,為了便于開發(fā)使用,通常需要使用profiles進行多環(huán)境配置,所以本文給大家介紹了使用profiles進行多環(huán)境配置的代碼實現(xiàn),需要的朋友可以參考下2024-02-02Java transient 關(guān)鍵字詳解及實例代碼
本文章向大家介紹Java transient關(guān)鍵字的使用方法和實例,包括的知識點有transient的作用、transient使用小結(jié)、transient使用細節(jié),需要的朋友可以參考一下2016-12-12SpringBoot整合Elasticsearch實現(xiàn)索引和文檔的操作方法
Elasticsearch 基于 Apache Lucene 構(gòu)建,采用 Java 編寫,并使用 Lucene 構(gòu)建索引、提供搜索功能,本文分步驟通過綜合案例給大家分享SpringBoot整合Elasticsearch的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2021-05-05