以下是 HashMap 遍历的几种方式,大概分为:
- 迭代器遍历
- for-each 遍历
- lambda 遍历
- stream 遍历
ps:使用 entrySet 遍历的效率比使用 keySet 遍历的效率要快一倍,所以我们可以尽量使用 entry 来遍历 map。
public class Test11 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "🦅");
map.put(2, "🐇");
map.put(3, "🐘");
map.put(4, "🦁");
map.put(5, "🐅");
map.put(6, "🐸");
// 迭代器遍历 entry
Iterator<Map.Entry<Integer, String>> iterator1 = map.entrySet().iterator();
while (iterator1.hasNext()) {
Map.Entry<Integer, String> entry = iterator1.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// 迭代器遍历 keySet
Iterator<Integer> iterator2 = map.keySet().iterator();
while (iterator2.hasNext()) {
int k = iterator2.next();
System.out.println(k);
System.out.println(map.get(k));
}
// for-each 遍历 entry
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// for-each 遍历 keySet
for (Integer k : map.keySet()) {
System.out.println(k);
System.out.println(map.get(k));
}
// lambda 表达式遍历
map.forEach((k, v) -> {
System.out.println(k);
System.out.println(v);
});
/*map.entrySet().forEach(entry -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});*/
/*map.keySet().forEach(k -> {
System.out.println(k);
System.out.println(map.get(k));
});*/
// stream 单线程遍历
map.entrySet().stream().forEach(entry -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
// stream 多线程遍历
map.entrySet().parallelStream().forEach(entry -> {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
});
}
}