阅读量:0
有多种方法可以遍历HashMap:
- 使用Iterator遍历:
HashMap map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); Iterator> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = iterator.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
- 使用for-each循环遍历entrySet():
for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
- 遍历所有key:
for (String key : map.keySet()) { System.out.println("Key = " + key + ", Value = " + map.get(key)); }
- 遍历所有value:
for (Integer value : map.values()) { System.out.println("Value = " + value); }
这些是常见的遍历HashMap的方法,选择适合自己需求的方法进行遍历即可。