Я пишу код для циклического прохождения по нескольким различным типам списков и создания другого на основе некоторых бизнес-проверок с использованием лямбда-выражений java 8.
Бизнес-проверка / логика:
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.
Класс модели:
class ServiceMap{
Integer serviceMapId;
Integer serviceId;
boolean isActive;
Integer updatedBy;
Calendar updatedDate;
}
Код:
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);
}
});
});
Есть ли способ достичь вышеупомянутой логики самым простым способом?