1. 程式人生 > >遍歷Set集合remove掉不需要的資料,List不能在遍歷的時候remove

遍歷Set集合remove掉不需要的資料,List不能在遍歷的時候remove

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);