java开发中常常会用到遍历,所以下边就列举四种map的遍历方法。
public class testMap { public static void main(String[] args) { Map<Object, Object> map = new HashMap<Object, Object>(); map.put("01", "A"); map.put("02", "B"); map.put("03", "C"); // test1(map); // test2(map); // test3_1(map); // test3_2(map); test4(map); } /** * 遍历map方法一 * * @param map */ public static void test1(Map<Object, Object> map) { for (Entry<Object, Object> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } /** * 遍历map方法二 * * @param map */ public static void test2(Map<Object, Object> map) { // 遍历map中的键 for (Object key : map.keySet()) { System.out.println("Key = " + key); } // 遍历map中的值 for (Object value : map.values()) { System.out.println("Value = " + value); } } /** * 遍历map方法三(非泛型) * * @param map */ public static void test3_1(Map<Object, Object> map) { Iterator<Entry<Object, Object>> entries = map.entrySet().iterator(); Entry<Object, Object> entry; while (entries.hasNext()) { entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } /** * 遍历map方法三(泛型) * * @param map */ public static void test3_2(Map<Object, Object> map) { Iterator entries = map.entrySet().iterator(); Entry entry; while (entries.hasNext()) { entry = (Entry) entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } /** * 遍历map方法四 * * @param map */ public static void test4(Map<Object, Object> map) { for (Object key : map.keySet()) { System.out.println("Key = " + key + ", Value = " + map.get(key)); } } }