在 Java 中,HashMap 是一種常用的集合類別,用來儲存「鍵-值(Key-Value)」對映射的資料結構。它允許透過鍵快速存取對應的值,底層基於哈希表實現。
PS.HashMap 不支援原始資料型別(Primitive Types)作為鍵或值,必須使用對應的包裝類別(Wrapper Classes)來宣告。
// 創建一個 HashMap,Key 為 int Value 為 String
HashMap<Integer, String> items = new HashMap<Integer, String>();
在 HashMap 中,Key 並不限制為 String,也可以是 Integer、Character 等物件類型
map.put(Key, Value);//新增
map.get(Key);//取得指定Key的Value
map.containsKey("banana") //檢查是否有名為banana的Key
map.keySet() //取得所有鍵(Key)的集合。
map.remove("orange") //移除key名為orange的Key跟Value
首先我們先建立一個HashMap,並用.put新增3筆資料,key是水果的名稱,value是該水果的價格,然後用.get(key)來取得該key的value,
// 建立 HashMap,並加上測試資料
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 50);
map.put("banana", 30);
map.put("orange", 20);
// 取得 apple 價格
int applePrice = map.get("apple");
Log.d(TAG, "蘋果價格: " + applePrice);
接下來,我們可以用containsKey("banana")來查詢是否有banana這個key,用.remove(key)來移除該key及其對應的value,這樣再用for迴圈遍歷所有 Key-Value後就會發現orange跟對應的20消失了
// 檢查 HashMap 是否含有鍵 "banana"
if (map.containsKey("banana")) {
Log.d(TAG, "有香蕉!");
}
// 移除 orange
map.remove("orange");
// 遍歷所有 Key-Value
for (String key : map.keySet()) {
int value = map.get(key);
Log.d(TAG, key + " = " + value);
}
entrySet()會回傳一個 Set,裡面是所有的鍵值對物件,map.keySet()適用於小量資料查詢,當你需要同時取得 HashMap 的 Key 和 Value ,或是map較大且只需要鍵值對,使用 entrySet() 效率會更高
因為使用 map.keySet() + map.get(key) 每次都需透過Key查找一次對應的Value,可能造成額外效能開銷,而 entrySet() 則直接提供鍵值對物件(Entry),效能更高
// 用 entrySet 方式遍歷
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
int value = entry.getValue();
Log.d(TAG, key + " = " + value);
}