Java之Map遍歷方式性能分析:ketSet與entrySet

keySet(): 將Map中全部的鍵存入到Set集合中。由於set具有迭代器,因此能夠以迭代方式取出全部的鍵,再根據get方法獲取每個鍵對應的值,其僅能經過get()取key。
entrySet():   返回此映射中包含的映射關係的 Set 視圖,格式爲Set<Map.Entry<K,V>>, Map.Entry表示映射關係,迭代後能夠e.getKey()、e.getValue()取key和value,返回的是Entry接口 。 
keySet()方式
Set<String> keySet = map.keySet();//先獲取map集合的全部鍵的Set集合
Iterator<String> it = keySet.iterator();//有了Set集合,就能夠獲取其迭代器
while (it.hasNext()) {
String key = it.next();
String value = map.get(key);//有了鍵能夠經過map集合的get方法獲取其對應的值。
}
entrySet()方式: 
//經過entrySet()方法將map集合中的映射關係取出(這個關係就是Map.Entry類型)
Set<Map.Entry<String, String>> entrySet = map.entrySet();
//將關係集合entrySet進行迭代,存放到迭代器中
Iterator<Map.Entry<String, String>> it2 = entrySet.iterator();
while (it2.hasNext()) {
Map.Entry<String, String> me = it2.next();//獲取Map.Entry關係對象me
String key2 = me.getKey();//經過關係對象獲取key
String value2 = me.getValue();//經過關係對象獲取value
}
性能測試:
public static void main(String[] args) {
HashMap<String, String> keySetMap = new HashMap<String, String>();
HashMap<String, String> entrySetMap = new HashMap<String, String>();
for (int i = 0; i < 100000; i++) {
keySetMap.put("" + i, "keySet");
entrySetMap.put("" + i, "entrySet");
}
long startTimeOne = System.currentTimeMillis();
Iterator<String> keySetIterator = keySetMap.keySet().iterator();
while (keySetIterator.hasNext()) {
String key = keySetIterator.next();
String value = keySetMap.get(key);
System.out.println(key + "," + value);
}
System.out.println("keyset spent times:" + (System.currentTimeMillis() - startTimeOne));

long startTimeTwo = System.currentTimeMillis();
Iterator<Map.Entry<String, String>> entryKeyIterator = entrySetMap.entrySet().iterator();
while (entryKeyIterator.hasNext()) {
Map.Entry<String, String> e = entryKeyIterator.next();
System.out.println(e.getKey() + "," + e.getValue());
}
System.out.println("entrySet spent times:" + (System.currentTimeMillis() - startTimeTwo));
}
運行結果以下所示,keySet()比entrySet()慢不少。

緣由分析:採用keySet方式時, 註釋掉keySetMap.get(key)後性能一致。以下圖所示,也就是說經過keySet方式獲取value時又從新遍歷Map集合,損耗了性能。所以不建議採用keySet方式獲取value。



相關文章
相關標籤/搜索