HashMap 遍历
HashMap 遍历从大的方向来说,可分为以下 4 类:
迭代器(Iterator)方式遍历;
For Each 方式遍历;
Lambda 表达式遍历(JDK 1.8+);
Streams API 遍历(JDK 1.8+)。
但每种类型下又有不同的实现方式,因此具体的遍历方式又可以分为以下 7 种:
使用迭代器(Iterator)EntrySet 的方式进行遍历;
使用迭代器(Iterator)KeySet 的方式进行遍历;
使用 For Each EntrySet 的方式进行遍历;
使用 For Each KeySet 的方式进行遍历;
使用 Lambda 表达式的方式进行遍历;
使用 Streams API 单线程的方式进行遍历;
使用 Streams API 多线程的方式进行遍历。
//ForEach EntrySet
for (Map.Entry<String,String> me :resultMap.entrySet()){
System.out.println("EntrySet "+me.getKey() +" = "+ me.getValue());
}
//ForEach keySet
for (String key : resultMap.keySet()){
System.out.println("keySet "+key +" = "+ resultMap.get(key));
}
//Lambda forEach
resultMap.forEach((key,value) -> {
System.out.println("Lambda forEach " + key +" = "+value);
});
//Streams API 单线程
resultMap.entrySet().stream().forEach((entry)->{
System.out.println("Streams API 单线程 " + entry.getKey() +" = "+entry.getValue());
});
//Streams API 多线程
resultMap.entrySet().parallelStream().forEach