循环多个不同类型的列表,并使用Java 8 Lambda表达式创建另一个列表

时间:2018-09-26 06:30:35

标签: java lambda java-8 java-stream

我正在编写代码以遍历多个不同类型的列表,并使用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);
        }
    });

});

有什么方法可以以最简单的方式实现上述逻辑?

1 个答案:

答案 0 :(得分:1)

既不确定为什么要为列表A中的每个项目浏览列表B,也不确定为什么要使用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);
      });