Java遍历一个HashMap

该文章发布于 ,归类于 Java 0 条评论

1. 通过keySet()方式

通过keySet()获取所有键的Set集合,再迭代该键的集合获取值

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Mike", 10);
map.put("Jason", 20);

Map<String, Integer> map2 = new HashMap<String, Integer>();
map2.put("Michael", 23);
map2.putAll(map);

System.out.println(map2);

Set<String> keys = map2.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
    String key = it.next();
    Integer value = map2.get(key);
    System.out.println("key=" + key + " value=" + value);
}

2. 使用Map.Entry

通过Map中的entrySet()方法获取存放Map.Entry<K,V>对象的Set集合

Set<Map.Entry<String, Integer>> entrySet = map2.entrySet();
Iterator<Map.Entry<String, Integer>> it = entrySet.iterator();
while (it.hasNext()) {
    Map.Entry<String, Integer> mapEntry = it.next();
    String key = mapEntry.getKey();
    Integer value = mapEntry.getValue();

    System.out.println("key=" + key + " value=" + value);
}

相关文章