2017-09-15 22 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會給你的列表中。

相關問題