android遍历map的五种方法

定义一个map 

Map<String, String> map = new HashMap<>();
map.put("id", "1024");
map.put("name", "张三");
map.put("sex", "男");
map.put("age", "30");

方式一:

for (Map.Entry<String, String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println("方式一:  " + "Key = " + key + "  ----  " + "Value = " + value);
}

方式二:

Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<String, String> entry = entries.next();
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println("方式二:  " + "Key = " + key + "  ----  " + "Value = " + value);
}

方式三:

for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
    Object obj = i.next();
    if (obj instanceof String) {
        String key = (String) obj;
        System.out.println("方式三:  " + "Key = " + key + "  ----  " + "Value = " + map.get(key));
    }
}

方式四:

for (String key : map.keySet()) {
    String value = map.get(key);
    System.out.println("方式四:  " + "Key = " + key + "  ----  " + "Value = " + value);
}

方式五:

for (String value : map.values()) {
    System.out.println("方式五:  " + "Value = " + value);
}

运行效果图:

android遍历map的五种方法