溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java中遍歷ConcurrentHashMap的四種方式分別是什么

發布時間:2021-12-08 17:43:00 來源:億速云 閱讀:180 作者:柒染 欄目:編程語言

本篇文章給大家分享的是有關Java中遍歷ConcurrentHashMap的四種方式分別是什么,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

方式一:在for-each循環中使用entries來遍歷

System.out.println("方式一:在for-each循環中使用entries來遍歷");

for (Map.Entry<String, String> entry: map.entrySet()) {

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

 }

方法二:在for-each循環中遍歷keys或values,這種方式適用于需要值或者鍵的情況,方法二比方法一快了10%

System.out.println("方法二:在for-each循環中遍歷keys或values,這種方式適用于需要值或者鍵的情況");//遍歷鍵for (String key : map.keySet()) {System.out.println("key = " + key);}//遍歷值for (String value : map.values()) {System.out.println("value = " + value);}

方法三:使用Iterator遍歷,使用并發集合不會報異常,性能類似于方法二

//使用泛型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);

}

方式四:通過鍵找值遍歷,該方法效率相當低,不建議使用

System.out.println("方式四:通過鍵找值遍歷");

for (String key : map.keySet()) {String value = map.get(key);

System.out.println("Key = " + key + ", Value = " + value);

 }

}

以上就是Java中遍歷ConcurrentHashMap的四種方式分別是什么,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女