I have a DTO that contains a list where I add or I remove some items, in my DAO when I get this list, I want to compare it with the existing one, so all new items that doesn't exist in the old list will be added, and the items in the old list that doesn't exist in the list in the dto will be deleted. for example, this is the items in the list that already exist :
[a,b,c]
And the list in the dto contains this :
[b,d]
So in this case [d]
will be inserted and [a]
and [c]
will be removed.
There is an approach where I can just deleted the old list and then add all the elements in the DTO's list, but I don't want it in this way.
This is what I tried :
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()));
}
}
So the first time I will look in the old list if it contains an item in the DTO's list, if it doesn't I will add it. In the second time I will look in the DTO's list if it contains an item in the old list, if it doesn't I wll remove it.
In this approach I have created two loops, each loop contains an intern loop, which looks too long.
Isn't there any other approach I can do it ? or using the Java 8 stream which will make it look better?
If you can re-model your data structure as a Set (and since you are comparing by id it seems you can do so by just making Profil's hashCode/equals do so), you can easily get it done using Guava's Sets class:
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);
Or using Java 8's 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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments