1.遍歷鍵值對
使用map.entrySet(),注意foreach語句中的類型為Map.Entry<K, V>
2.遍歷Key
使用map.keySet()
3.遍歷Value
使用map.values()
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("一", 1);
map.put("二", 2);
map.put("三", 3);
// 1.遍歷鍵值對,使用Map.Entry,map.entrySet()
System.out.println("=====遍歷鍵值對=====");
for (Map.Entry<String, Integer> i : map.entrySet()) {
System.out.print("Key:" + i.getKey() + " ");
System.out.println("Value:" + i.getValue());
}
// 2.遍歷Key,使用map.keySet()
System.out.println("=====遍歷Key=====");
for (String i : map.keySet()) {
System.out.println("Key:" + i);
}
// 3.遍歷Value,使用map.entrySet
System.out.println("=====遍歷Value=====");
for (int i : map.values()) {
System.out.println("Value:" + i);
}
}
=====遍歷鍵值對===== Key:一 Value:1 Key:三 Value:3 Key:二 Value:2 =====遍歷Key===== Key:一 Key:三 Key:二 =====遍歷Value===== Value:1 Value:3 Value:2
