在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);
}