有多種方法可以遍歷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的方法,選擇適合自己需求的方法進行遍歷即可。