0
点赞
收藏
分享

微信扫一扫

Java Map集合的几种遍历方式与性能对比(包含lambda表达式)

实例代码如下:

public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
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<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> 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<String, String> 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);
}

运行结果如下:
Java Map集合的几种遍历方式与性能对比(包含lambda表达式)_加载
综上所述:第三种遍历方式在数据量非常小时是最好的,第五种遍历方式是最简单粗暴的。
Java Map集合的几种遍历方式与性能对比(包含lambda表达式)_提高效率_02关于lambda表达式的用法可以参照:
​java8 lambda forEach循环与增强for循环性能对比



举报

相关推荐

0 条评论