I am writing a code to loop through multiple different type of lists and create another based on some business validations using java 8 lambda expressions.
Business Validation/Logic:
there are 2 lists List<ServiceMap> listA and List<Integer> listB
1. if the element in listA not present in listB then deactivate that record in DB.
2. if the element in listA present in listB then activate that record in DB.
3. if the element in listB not present in listA then create new record in DB.
Model class:
class ServiceMap{
Integer serviceMapId;
Integer serviceId;
boolean isActive;
Integer updatedBy;
Calendar updatedDate;
}
Code:
List<ServiceMap> listA = getServiceMaps();//Will get from database
List<Integer> listB = Arrays.asList(1, 10, 9);//Will get from client
List<ServiceMap> listC = new ArrayList<>();//Building new list by validating records from both lists above
listA.stream().forEach(e -> {
//noneMatch means we have to deactivate record in DB
if (listB.parallelStream().noneMatch(x -> x == e.getServiceId())) {
ServiceMap recordToDeactivate = e;
e.setIsActive(false);
listC.add(recordToDeactivate);
return;
}
listB.stream().forEach(x -> {
// if the record already added to listC then continue to next record
if (listC.stream().anyMatch(e2->e2.getServiceId() == x)) {
return;
}
//Matched means we have to activate record in DB
if (x == e.getServiceId()) {
ServiceMap recordToActivate = e;
e.setIsActive(true);
listC.add(recordToActivate);
return;
} else {
//Not Matched means create new record in DB
ServiceMap newM = new ServiceMap();
newM.setIsActive(true);
newM.setServiceId(x);
listC.add(newM);
}
});
});
Is there any way to achieve above logic in simplest way ?