代码如下:
public static void main(String[] args) {
Map map = new HashMap();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
long l1 = System.nanoTime();
// 第一种遍历方式
System.out.println("第一种遍历方式:通过遍历 Map 的 keySet,遍历 Key 和 Value");
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
long l2 = System.nanoTime();
// 第二种遍历方式(如果在遍历过程中,有删除某些Key-Value的需求,可以使用这种遍历方式)
System.out.println("\n第二种遍历方式:通过Iterator 迭代器遍历 Key 和 Value");
Iterator> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
long l3 = System.nanoTime();
// 第三种遍历方式(推荐,尤其是容量大时)
System.out.println("\n第三种遍历方式:通过遍历 Map 的 entrySet,遍历 Key 和 Value");
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
long l4 = System.nanoTime();
// 第四种遍历方式
System.out.println("\n第四种遍历方式:通过遍历 Map 的 values,只能遍历 Value,获取不到对应的 Key");
for (String value : map.values()) {
System.out.println("Value: " + value);
}
long l5 = System.nanoTime();
// 第五种遍历方式(JDK 1.8支持的 Lambda 表达式,强烈推荐!!!)
System.out.println("\n第五种遍历方式:通过 Lambda 表达式,遍历 Key 和 Value");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
long l6 = System.nanoTime();
// 第五种遍历方式(JDK 1.8支持的 Lambda 表达式,强烈推荐!!!)
System.out.println("\n第五种遍历方式:通过 Lambda 表达式,遍历 Key 和 Value");
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
long l7 = System.nanoTime();
System.out.println("1----" + (l2 - l1) / 1000);
System.out.println("2----" + (l3 - l2) / 1000);
System.out.println("3----" + (l4 - l3) / 1000);
System.out.println("4----" + (l5 - l4) / 1000);
System.out.println("5----" + (l6 - l5) / 1000);
System.out.println("6----" + (l7 - l6) / 1000);
}
运行结果如下:
综上所述:第三种遍历方式在数据量非常小时是最好的,第五种遍历方式是最简单粗暴的。
如 果 数 据 量 特 别 大 时 , 推 荐 使 用 第 五 种 方 式 , 但 是 需 要 在 项 目 启 动 时 就 加 载 , 这 样 可 以 大 大 提 高 效 率。
如果数据量特别大时,推荐使用第五种方式,但是需要在项目启动时就加载,这样可以大大提高效率}如果数据量特别大时,推荐使用第五种方式,但是需要在项目启动时就加载,这样可以大大提高效率。