我有一個DTO包含一個列表,我添加或刪除了一些項目,在我的DAO中,當我得到這個列表時,我想將它與現有的項目進行比較,所以所有舊列表中不存在的新項目將被添加,舊列表中不存在於dto列表中的項目將被刪除。 例如,這是在列表中已存在的項目:檢查元素是否存在於使用Java的數組中8
[a,b,c]
而且在DTO的列表包含此:
[b,d]
因此,在這種情況下[d]
會被插入,[a]
和[c]
將被刪除。
有一種方法,我可以刪除舊列表,然後添加DTO列表中的所有元素,但我不希望這樣。
這是我的嘗試:
public Role updateRoleDTO(final RoleDTO roleDTO) {
//...
//... Some code
//...
boolean profilExist = false;
RoleProfil roleProfil = null;
// Add non existing profils
for (Profil profil : roleDTO.getProfils()) {
profilExist = false;
roleProfil = new RoleProfil();
for(Profil oldProfil : oldProfilsList){
if(profil.getId().equals(oldProfil.getId())){
profilExist = true;
break;
}
}
if(!profilExist){
roleProfil.setRoleId(insertedRole);
roleProfil.setProfilId(profil);
roleProfilDAO.insert(roleProfil);
}
}
//Remove existing profils that are not in the updated Role
for(Profil oldProfil : oldProfilsList){
profilExist = false;
for (Profil profil : roleDTO.getProfils()) {
if(oldProfil.getId().equals(profil.getId())){
profilExist = true;
break;
}
}
if(!profilExist){
roleProfilDAO.delete(roleProfilDAO.findRoleProfilByRoleIdAndProfilId(roleDTO.getRoleId(), oldProfil.getId()));
}
}
所以第一次我會看在舊列表,如果它包含在DTO的列表中的項目,如果沒有,我會添加它。 第二次我會查看DTO的列表,如果它包含舊列表中的項目,如果它不包含,我將刪除它。
在這種方法中,我創建了兩個循環,每個循環都包含一個內部循環,這看起來太長了。
難道沒有其他辦法可以做到嗎?或使用Java 8流,這將使它看起來更好?
(1)避免可變列表。 (2)然後你可以做'obj.list = newList' – slim
我不明白你的例子:''[a,b,c] [b,d]' - >'[d]'將被插入並且'[a]'將被刪除「。 - 爲什麼不去掉'c'? – slim
@slim obj.list = newList在我的情況下不起作用,因爲obj不知道爲什麼我創建DTO的列表,列表中的項目將插入另一個對象中。 –