java使用迭代器删除元素_使用Java从地图中删除元素
java使用迭代器刪除元素
關于從Java中的Map刪除元素的非常簡短的文章。 我們將專注于刪除多個元素,而忽略了您可以使用Map.remove刪除單個元素的Map.remove 。
以下Map將用于此帖子:
Map<Integer, String> map = new HashMap<>(); map.put(1, "value 1"); map.put(2, "value 2"); map.put(3, "value 3"); map.put(4, "value 4"); map.put(5, "value 5");有幾種刪除元素的方法。 您可以手動遍歷代碼并將其刪除:
for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext(); ) {Integer key = iterator.next();if(key != 1) {iterator.remove();} }這是您無需訪問Java 8+即可執行的操作。 從Map刪除元素時,需要Iterator來防止ConcurrentModificationException 。
如果您確實有權使用Java(8+)的較新版本,則可以從以下選項中進行選擇:
// remove by value map.values().removeIf(value -> !value.contains("1")); // remove by key map.keySet().removeIf(key -> key != 1); // remove by entry / combination of key + value map.entrySet().removeIf(entry -> entry.getKey() != 1);removeIf是Collection可用的方法。 是的, Map本身不是Collection ,也無權訪問removeIf本身。 但是,通過使用: values , keySet或entrySet ,將返回Map內容的視圖。 該視圖實現Collection允許在其上調用removeIf 。
由values , keySet和entrySet返回的內容非常重要。 以下是JavaDoc的values摘錄:
* Returns a { this map. Collection} view of the values contained in * Returns a { @link Collection} view of the values contained in map. * The collection is backed by the map, so changes to the map are * reflected in the collection, and vice-versa. * * The collection supports element removal, which removes the corresponding * mapping from the map, via the { @code Iterator.remove}, * mapping from the map, via the { Iterator.remove}, * { @code Collection.remove}, { @code removeAll}, * { @code retainAll} and { @code clear} operations.此JavaDoc解釋說,由values返回的Collection由Map支持,并且更改Collection或Map都會改變另一個。 我認為我無法解釋JavaDoc所說的內容,而不是那里已經寫的內容。因此,我現在將不再嘗試該部分。 我只顯示了values的文檔,但是當我說keySet和entrySet也都由Map的內容作為后盾時,您可以信任我。 如果您不相信我,可以自己閱讀文檔。
這也使用舊版 Java版本鏈接回第一個示例。 該文檔指定可以使用Iterator.remove 。 這是早先使用的。 此外, removeIf的實現與Iterator示例非常相似。 討論完之后,我不妨展示一下:
default boolean removeIf(Predicate<? super E> filter) {Objects.requireNonNull(filter);boolean removed = false;final Iterator<E> each = iterator();while (each.hasNext()) {if (filter.test(each.next())) {each.remove();removed = true;}}return removed; }還有一些額外的東西。 但是,否則幾乎是相同的。
就是這樣。 除了讓我記住要告訴您的記住以外,沒有太多結論了:使用values , keySet或entrySet將提供對removeIf訪問,從而允許輕松刪除Map條目。
翻譯自: https://www.javacodegeeks.com/2019/03/removing-elements-map-java.html
java使用迭代器刪除元素
總結
以上是生活随笔為你收集整理的java使用迭代器删除元素_使用Java从地图中删除元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 域名怎么跟服务器绑定(域名绑定服务器)
- 下一篇: bom .dom_MicroProfil