java_基础_遍历map删除元素_Java 遍历Map(包括集合)时,修改删除元素

转载自:https://blog.csdn.net/weixin_33498283/article/details/114071025

1、遍历Map集合的四种方法

public staticvoid main(String[] args) {
    
    


// 构建一个Map 初始值为3条数据

Map map = new HashMap();

map.put("1", "xiaqiu");

map.put("2", "pangzi");

map.put("3", "shouzi");

//第一种:普遍使用,二次取值

System.out.println("通过Map.keySet遍历key和value:");

for (String key : map.keySet()) {
    
    

System.out.println("key= "+ key + " and value= " + map.get(key));

}

//第二种:通过[Iterator](https://so.csdn.net/so/search?q=Iterator&spm=1001.2101.3001.7020)迭代器遍历循环Map.entrySet().iterator();

System.out.println("通过Map.entrySet使用iterator遍历key和value:");

Iterator> it = map.entrySet().iterator();

while (it.hasNext()) {
    
    

Map.Entry entry = it.next();

System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

}

//第三种:笔者推荐,尤其是容量大时(相对来说 比2好一点 效率高)

System.out.println("通过Map.entrySet遍历key和value");

for (Map.Entry entry : map.entrySet()) {
    
    

System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

}

//第四种

System.out.println("通过Map.values()遍历所有的value,但不能遍历key");

for (String v : map.values()) {
    
    

System.out.println("value= " + v);

}

}

下面这种可以在遍历的时候修改和删除元素

Iterator> it = map.entrySet().iterator();

while(it.hasNext()){
    
    
	Map.Entry entry=it.next();
	if(AssertUtil.isEmpty(entry.getValue())){
    
    
		it.remove();
	}else{
    
    

	if("systemId".equals(entry.getKey())){
    
    
		continue;
	}

	map.put(entry.getKey(),"%"+entry.getValue()+"%");
	}
}

List 在

(1). 使用索引遍历的时候删除不会有异常,但是后续的数据可能会有问题;

(2). List用增强的for循环遍历时:会报告异常java.util.ConcurrentModificationException

(删除完立马break的除外)

(3). 迭代器迭代时,使用迭代器iterator.remove()不会有问题。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42420293/article/details/124862391