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