2017-09-15 76 views
1

我有一个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流,这将使它看起来更好?

+0

(1)避免可变列表。 (2)然后你可以做'obj.list = newList' – slim

+1

我不明白你的例子:''[a,b,c] [b,d]' - >'[d]'将被插入并且'[a]'将被删除“。 - 为什么不去掉'c'? – slim

+0

@slim obj.list = newList在我的情况下不起作用,因为obj不知道为什么我创建DTO的列表,列表中的项目将插入另一个对象中。 –

回答

1

如果你可以重新建模你的数据结构作为一个集合(因为你是通过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的流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); 
0
oldProfilsList.addAll(roleDTO.getProfils()); 
    oldProfilsList.removeIf(op ->!roleDTO.getProfils().contain(oldProfile)); 
    oldProfilsList = new ArrayList<Profile>(new HashSet<Profile>(oldProfilsList)) 

oldProfilsList会给你的列表中。