gpt4 book ai didi

java - 循环多个不同类型的列表并使用 java 8 lambda 表达式创建另一个列表

转载 作者:行者123 更新时间:2023-12-02 10:46:34 24 4
gpt4 key购买 nike

我正在编写一个代码来循环访问多个不同类型的列表,并使用 java 8 lambda 表达式基于一些业务验证创建另一个列表。

业务验证/逻辑:

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);
}
});

});

有没有办法以最简单的方式实现上述逻辑?

最佳答案

不知道为什么要通过列表 B 流式传输列表 A 中的每个项目。也不知道为什么要使用 Streams。

List<Integer> notInA = new ArrayList<>(listB);
listA.forEach(sm -> {
notInA.remove(a.getServiceId());
sm.setActive(listB.contains(sm.getServiceId()));
listC.add(sm);
});

notInA.forEach(id -> {
ServiceMap newMap = new ServiceMap(id);
newMap.setActive(true);
listC.add(newMap);
});

关于java - 循环多个不同类型的列表并使用 java 8 lambda 表达式创建另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52511305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com