一、Map.remove()
Map.remove(Object key)方法用於根據key刪除Map中的entry。如果Map中不存在這個key,則不進行任何操作。remove()方法在執行刪除操作後會返回被刪除的value值,或是null。
Map map = new HashMap(); map.put(1, "a"); String value = map.remove(1); System.out.println(value); // 輸出a System.out.println(map.containsKey(1)); // 輸出false
上面代碼中,通過remove()方法刪除了key為1的entry,並返回了對應的value值”a”。使用containsKey()方法查看發現在Map中已經不存在key為1的entry,返回false。
二、Map.remove()用法小技巧
1. 使用remove()方法批量刪除符合條件entries
remove()方法不僅可以刪除單個entry,還可以用於批量刪除符合條件的entries。可以通過循環遍歷或Java 8中的stream()方法實現。
// 循環遍歷刪除 Map map = new HashMap(); for (Iterator<Map.Entry> it = map.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = it.next(); if (entry.getValue() == 0) { it.remove(); } } // Java 8中的stream()方法實現 Map map = new HashMap(); map.entrySet().removeIf(entry -> entry.getValue() == 0);
上述代碼中,使用removeIf()方法批量刪除value為0的entry。
2. 使用remove()方法實現LRU緩存淘汰策略
LRU(Least Recently Used)緩存淘汰策略是指在緩存容量不夠時,優先刪除使用時間距離當前時間最久的entry。可以使用LinkedHashMap實現LRU緩存淘汰策略,LinkedHashMap繼承自HashMap,內部是由一個linked list實現的,它保留了entry插入的順序。
public class LRUCache extends LinkedHashMap { private final int maxEntries; public LRUCache(int maxEntries) { super(16, 0.75f, true); this.maxEntries = maxEntries; } // LinkedHashMap自帶的刪除最舊entry的辦法,被覆蓋時會調用這個方法 protected boolean removeEldestEntry(Map.Entry eldest) { return size() > maxEntries; } } // 測試使用 LRUCache map = new LRUCache(2); map.put(1, 1); map.put(2, 2); map.put(3, 3); map.put(4, 4); System.out.println(map);
在上述代碼中,定義了一個LRUCache類,它繼承自LinkedHashMap,並覆蓋了removeEldestEntry()方法,實現LRU緩存淘汰策略。在測試使用時,map容量為2,但是存放了4個entry,因此會自動刪除最久未使用的entry。
三、注意事項
1. Java集合類本身不是線程安全的
Java中的集合類本身是不具備線程安全性的,因為多個線程同時修改集合中的entry時,存在同時讀寫集合的問題。因此,在並發環境中使用集合類時,需要通過加鎖或並發包提供的類來保證線程安全。
2. 在遍歷集合時,不要使用循環表達式中的remove()方法
使用循環表達式中的remove()方法刪除entry會導致遍歷集合出現異常或遺漏元素。因為在使用remove()方法刪除entry後,下一個元素會頂替刪除的元素,因此遍歷時可能會跳過頂替位置變化後的元素。
最後,上面提到的LRU緩存淘汰策略在Java 8中還可以通過Java 8提供的LinkedHashMap的一些新特性很好地實現,感興趣的可以自己去了解。
原創文章,作者:QKTNT,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/370045.html