HashMap集合7种常见遍历方式
解决方法
1.iterator迭代器进行Entry遍历(此方法效率最佳)
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<Integer, String> next = iterator.next();
System.out.println(next.getKey());
System.out.println(next.getValue());
}
2.iterator迭代器进行KeySet遍历
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()){
Integer key = iterator.next();
System.out.print(key);
System.out.print(map.get(key));
}
3.ForEach的EntrySet方式进行遍历
for (Map.Entry<Integer,String> entry: map.entrySet()) {
System.out.println("entry.getKey() = " + entry.getKey());
System.out.println("entry.getValue() = " + entry.getValue());
}
4.ForEach的KeySet方式进行遍历
for (Interger key: map.keySet()) {
System.out.print(key);
System.out.print(map.get(key));
}
5.Lambda 表达式进行遍历
map.forEach((key,value) -> {
System.out.print(key);
System.out.print(value);
});
6. Streams API 单线程的方式进行遍历
map.entrySet().stream().forEach((integerStringEntry -> {
System.out.println(integerStringEntry.getKey());
System.out.println(integerStringEntry.getValue());
}));
7.Streams多线程并发的方式进行遍历
map.entrySet().parallelStream().forEach((integerStringEntry -> {
System.out.println(integerStringEntry.getKey());
System.out.println(integerStringEntry.getValue());
}));