日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java map removeall_Java删除Map中元素

發布時間:2024/9/27 java 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java map removeall_Java删除Map中元素 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言:

關于Java從Map中刪除元素的使用,可以使用刪除單個元素的事實Map.remove。

示例:

初始化一個Map對象

Map 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 iterator = map.keySet().iterator(); iterator.hasNext(); ) {

Integer key = iterator.next();

if(key != 1) {

iterator.remove();

}

}

如果不使用Java 8+,就可以使用Iterator以防止?ConcurrentModificationException異常。

如果您使用的較新版本的Java(8+),那么您可以這樣:

// 通過value移除

map.values().removeIf(value -> !value.contains("1"));

// 通過key移除

map.keySet().removeIf(key -> key != 1);

// 通過鍵/值的輸入/組合刪除

map.entrySet().removeIf(entry -> entry.getKey() != 1);

removeIf是Collections?的方法。一個Map本身不是一個Collection,也無法訪問removeIf自己。但是通過使用:values,keySet或entrySet此實現Collection允許removeIf在其上調用。

內容返回的values,keySet而且entrySet是非常重要的。以下是JavaDoc的說明摘要values:

* Returns a {@link Collection} view of the values contained in this 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},

* {@code Collection.remove}, {@code removeAll},

* {@code retainAll} and {@code clear} operations.

這個JavaDoc解釋了Collection返回的values是由它支持的。文檔指定Iterator.remove可以使用。此外實現removeIf與Iterator示例如下。

default boolean removeIf(Predicate super E> filter) {

Objects.requireNonNull(filter);

boolean removed = false;

final Iterator each = iterator();

while (each.hasNext()) {

if (filter.test(each.next())) {

each.remove();

removed = true;

}

}

return removed;

}

總結:

使用?values,keySet或entrySet接入removeIf 更容易移除Map中的元素。

總結

以上是生活随笔為你收集整理的java map removeall_Java删除Map中元素的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。