我有一个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的列表,列表中的项目将插入另一个对象中。 –