您的位置:首页 > 编程语言 > Java开发

Java HashMap 两种遍历方法性能比较

2014-07-06 17:25 816 查看
HashMap<String, Integer> map = new HashMap<>();

map.put("1", 111);
map.put("2", 222);
map.put("3", 333);
map.put("4", 444);
map.put("5", 555);

// This is the first way to get all the map element via Iterator with keySet.

long startTime = System.nanoTime();
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
System.out.print(key + ", ");
System.out.println(map.get(key));
}
long interval = System.nanoTime() - startTime;
System.out.println("interval1: " + interval);

// ======================================================================================================================

// This is the second way to get all the map element via Entry

long startTime2 = System.nanoTime();
Set<Entry<String, Integer>> sets = map.entrySet();
for (Entry<String, Integer> entry : sets) {
System.out.print(entry.getKey() + ", ");
System.out.println(entry.getValue());
}
long interval2 = System.nanoTime() - startTime2;
System.out.println("interval2: " + interval2);

First way result:

3, 333

2, 222

1, 111

5, 555

4, 444
interval1: 1152533

Second way result:

3, 333

2, 222

1, 111

5, 555

4, 444

interval2: 521673

It is obvious that the second way with
EntrySet is better than the first one with keySet!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: