一、使用 Iterator 遍历 HashMap EntrySet
public static void iteratorEntrySetMap(Map<Integer, String> map) { Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, String> entry = iterator.next(); System.out.println(entry.getKey()); System.out.println(entry.getValue()); } }
二、使用 Iterator 遍历 HashMap KeySet
public static void iteratorKeySetMap(Map<Integer, String> map) { Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()) { Integer key = iterator.next(); System.out.println(key); System.out.println(map.get(key)); } }
三、使用 For-each 循环遍历 HashMap
public static void forEachMap(Map<Integer, String> map) { for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); } }
四、使用 Lambda 表达式遍历 HashMap
public static void lambdaMap(Map<Integer, String> map) { map.forEach((key, value) -> { System.out.println(key); System.out.println(value); }); }
五、使用 Stream API 遍历 HashMap
public static void streamApiMap(Map<Integer, String> map) { map.entrySet().stream().forEach((entry) -> { System.out.println(entry.getKey()); System.out.println(entry.getValue()); }); }