我有一个 DTO,其中包含一个列表,我在其中添加或删除一些项目,在我的 DAO 中,当我获得此列表时,我想将其与现有列表进行比较,因此所有不存在于该列表中的新项目旧列表将被添加,旧列表中不存在于 dto 列表中的项目将被删除。 例如,这是列表中已存在的项目:
[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 流会让它看起来更好?
最佳答案
如果你可以将你的数据结构重新建模为一个集合(并且由于你通过 id 进行比较,似乎你可以通过使 Profil 的 hashCode/equals 这样做来做到这一点),你可以使用 Guava 的 Sets 类轻松完成它:
Set<String> oldSet = Sets.newHashSet("a", "b", "c");
Set<String> newSet = Sets.newHashSet("b", "d");
Sets.SetView<String> toRemove = Sets.difference(oldSet, newSet);
Sets.SetView<String> toInsert = Sets.difference(newSet, oldSet);
Sets.SetView<String> toUpdate = Sets.intersection(oldSet, newSet);
或者使用 Java 8 的 Streams API:
Set<String> oldSet = new HashSet<>(Arrays.asList("a", "b", "c"));
Set<String> newSet = new HashSet<>(Arrays.asList("b", "d"));
Stream<String> toRemove = oldSet.stream().filter(e -> !newSet.contains(e));
Stream<String> toInsert = newSet.stream().filter(e -> !oldSet.contains(e));
Stream<String> toUpdate = oldSet.stream().filter(newSet::contains);
关于java - 使用 Java 8 检查数组中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46243765/