在Java中,遍歷HashMap并取得其值可以通過以下幾種方法實現:
entrySet()
方法遍歷HashMap的鍵值對:HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
keySet()
方法遍歷HashMap的鍵,并通過鍵獲取對應的值:HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
values()
方法遍歷HashMap的值:HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String value : map.values()) {
System.out.println("Value: " + value);
}