一、HashMap簡介
HashMap是Java中的常用集合類,它實現了Map介面,提供了基於鍵值對的存儲和檢索功能。HashMap允許鍵和值都可以為空,而且是非線程安全的。
二、HashMap遍歷方式
1. 使用迭代器遍歷
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Tom", 1);
hashMap.put("Jerry", 2);
Iterator iter = hashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
Integer value = (Integer) entry.getValue();
System.out.println("key: " + key + ", value: " + value);
}
使用entrySet方法獲取HashMap的entry集合,然後通過迭代器遍歷集合,最後通過entry的getKey和getValue方法獲取鍵和值。
2. 使用foreach遍歷鍵
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Tom", 1);
hashMap.put("Jerry", 2);
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key);
}
使用keySet方法獲取HashMap的鍵集合,然後通過foreach循環遍歷鍵。
3. 使用foreach遍歷值
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Tom", 1);
hashMap.put("Jerry", 2);
for (Integer value : hashMap.values()) {
System.out.println("Value: " + value);
}
使用values方法獲取HashMap的值集合,然後通過foreach循環遍歷值。
三、HashMap遍歷性能對比
在實際開發中,多個遍歷方式的性能是有差異的,根據遍歷方式的不同,HashMap的遍歷時間也不同。
下面我們通過代碼來測試三種遍歷方式的性能:
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int i = 1; i <= 1000000; i++) {
hashMap.put(i, i);
}
long start = System.currentTimeMillis();
Iterator iter = hashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Integer key = (Integer) entry.getKey();
Integer value = (Integer) entry.getValue();
}
long end = System.currentTimeMillis();
System.out.println("Iterator: " + (end - start) + "ms");
start = System.currentTimeMillis();
for (Integer key : hashMap.keySet()) {
Integer value = hashMap.get(key);
}
end = System.currentTimeMillis();
System.out.println("Key Set: " + (end - start) + "ms");
start = System.currentTimeMillis();
for (Integer value : hashMap.values()) {
Integer key = getKey(hashMap, value);
}
end = System.currentTimeMillis();
System.out.println("Value: " + (end - start) + "ms");
private static Integer getKey(HashMap<Integer, Integer> map, Integer value) {
for (Integer key : map.keySet()) {
if (value.equals(map.get(key))) {
return key;
}
}
return null;
}
在這個測試代碼中,我們生成了一個包含1000000個鍵值對的HashMap,然後分別使用迭代器、keySet和values遍歷方式,每種方式遍歷一次,統計遍歷時間。
可以看到,keySet和values的性能表現大致相同,比迭代器快一點。
四、HashMap遍歷總結
HashMap是Java中常用的集合類,提供基於鍵值對的存儲和檢索功能。三種遍歷方式分別是使用迭代器、keySet和values,其中後兩種性能較好。
開發者在使用HashMap並進行遍歷時要結合實際情況選擇最適合自己的方式。
原創文章,作者:VSVCH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/333881.html