我是靠谱客的博主 欢呼书包,这篇文章主要介绍Map集合按key删除和按value删除,现在分享给大家,希望可以做个参考。

首先是按value删除,构建一个map集合,存放3个元素,通过map.values()拿到value的collection集合,再删除,这个比较简单

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class test { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); // 按值删除 map.put("1", "哈哈"); map.put("2", "嘿嘿"); map.put("3", "吼吼"); Collection<String> collect = map.values(); System.out.println(map); if (collect.contains("吼吼") == true) { collect.remove("吼吼"); } System.out.println(map); } }

在这里插入图片描述

注意!!!!!!!!!!!!!!!!!!!!!!
经人提醒,发现这里如果初始集合put第四个键值对,4=吼吼,经过这么操作,只能删掉第三个“吼吼”,最终的结果是{1=哈哈, 2=嘿嘿, 4=吼吼},这里修改,使用新map集合接收处理过的map:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class test { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); // 按值删除 map.put("1", "哈哈"); map.put("2", "嘿嘿"); map.put("3", "吼吼"); map.put("4", "吼吼"); Map<String, String> map2 = new HashMap<String, String>(); System.out.println(map); for (String key:map.keySet()) { String value = map.get(key); if (!value.equals("吼吼")){ map2.put(key,map.get(key)); } } System.out.println(map2); } }

根据key删除的实例是我在网上找的,这样运行会报错Exception in thread "main" java.util.ConcurrentModificationException

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class test { public static void main(String[] args) { Map<String, String> map = new HashMap(); // 按值删除 map.put("1", "哈哈"); map.put("2", "嘿嘿"); map.put("3", "吼吼"); // 按键删除 System.out.println(map); for (String s : map.keySet()) { // System.out.println(s); if (s == "1") { map.remove("1"); } } System.out.println(map); } }

在这里插入图片描述
但是如果删除的是最后一个元素,倒是可以正常删除
在这里插入图片描述
因为List,Set,Map迭代的时候是不允许自身长度改变的,所以在迭代的内部,不允许使用add、remove方法。
究其原因是java的foreach循环其实就是根据list、map对象创建一个Iterator迭代对象,用这个迭代对象来遍历list、map,相当于list、map对象中元素的遍历托管给了Iterator,你如果要对list、map进行增删操作,都必须经过Iterator,否则Iterator遍历时会乱,所以直接对list、map进行删除时,Iterator会抛出ConcurrentModificationException异常
解决办法:不要用for-each遍历,换成迭代器遍历,并且不要用集合的remove()方法移除对象,用迭代器的方法iterator.remove()移除对象

使用Map集合中的方法keySet(),把Map集合所有的key取出来,存储到一个Set集合中,iterator.hasNext() 判断是否有下个元素,用迭代器的remove去除元素

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class test { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); // 按值删除 map.put("1", "哈哈"); map.put("2", "嘿嘿"); map.put("3", "吼吼"); Collection<String> collect = map.values(); System.out.println(map); Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); while (it.hasNext()){ String key = it.next(); if (key == "2") { it.remove(); } } System.out.println(map); } }

在这里插入图片描述

最后

以上就是欢呼书包最近收集整理的关于Map集合按key删除和按value删除的全部内容,更多相关Map集合按key删除和按value删除内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部