欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

遍历Set集合remove掉不需要的数据,List不能在遍历的时候remove

程序员文章站 2022-07-12 20:42:55
...
for(Iterator<IAddress> it=addSet.iterator();it.hasNext();){
	IAddress address = it.next();
	if(address.getId() != null){
		Boolean flag = false;
		for(IAddress addr : set){
			if(addr.getId().equals(address.getId())){
				flag = true;
				break;
			}
		}
		if(!flag){
			it.remove();
		}
	}
}

 List遍历的时候不能直接 remove,实现办法是用 iterator.remove,否则会报ConcurrentModificationException 

 

 

注意set 在remove操作时set集合不能再有任何修改,否则hashcode发生改变,则不能remove成功

例如以下case

Hibernate.initialize(subAccount.getAuthorizors());


			if(subAccount.getAuthorizors() != null){
				
				Iterator<IAuthorizor> iterator = subAccount.getAuthorizors().iterator();
				
				while(iterator.hasNext()){
					
					IAuthorizor authorizor = iterator.next();
					
					if(authorizor != null){
					
						Hibernate.initialize(authorizor.getAuthorizorIDs());
						
						Hibernate.initialize(authorizor.getAuthorizorAddresses());

						Hibernate.initialize(authorizor.getAuthorizorPhones());

						Hibernate.initialize(authorizor.getNationality());
						
					}
					
				}
				
			}

authorizor 重新initialize之后,remove 不会成功,所以,可以将db取到的set copy 给一个新的set。再remove

Set<IAuthorizor> tempAuthSet = subAccount.getAuthorizors();//db data
Set<IAuthorizor> dbAuthSet = (Set<IAuthorizor>)ObjectUtil.deepCopy(tempAuthSet);
			//Delete authorizor
			for(Iterator<IAuthorizor> it = dbAuthSet.iterator();it.hasNext();){
				IAuthorizor dbAuthorizor = it.next();
			   if(dbAuthorizor.getId() != null){
					Boolean flag = false;
					for(IAuthorizor authorizor : authSet){
						if(authorizor.getId() != null){
							if(authorizor.getId().equals(dbAuthorizor.getId())){
								flag = true;
								break;
							}
						}
					}
					if(!flag){
						//it.remove();
						dbAuthSet.remove(dbAuthorizor);
					}
				}
			}
			
			dbAuthSet.addAll(addAuthSet);
			subAccount.setAuthorizors(dbAuthSet);

 

相关标签: set 遍历 iterator