简体   繁体   English

如何遍历多个列表并使用Java 8 Lambda表达式合并两个列表中的唯一值来创建另一个列表

[英]How to loop through multiple Lists and create another list with merging of unique values from both the lists using Java 8 lambda expressions

I am writing a code to loop through multiple Lists and create another list with merging of unique values from both the lists using Java 8 lambda expressions. 我正在编写代码以遍历多个列表,并使用Java 8 lambda表达式合并两个列表中的唯一值来创建另一个列表。

Model class: 型号类别:

class ServiceMap{
    Integer serviceMapId;
    Integer seviceId;
}

Code logic: 代码逻辑:

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 it merging of both lists above

listA.stream().forEach(e -> {
    if (listB.parallelStream().noneMatch(x -> x == e.getServiceId())) {
        listC.add(new ServiceMap(e.getServiceId()));
        return;
    }

    listB.stream().forEach(x -> {
        if (listC.stream().anyMatch(e2->e2.getServiceId() == x)) {
            return;
        }
        if (x == e.getServiceId()) {
            listC.add(new ServiceMap(e.getServiceId()));
        } else {
            listC.add(new ServiceMap(x));
        }
    });

});
listC.stream().forEach(x -> System.out.println(x));

Is it efficient way writing code using java lambda expressions? 使用Java Lambda表达式编写代码是否有效?

You could stream each list, apply distinct to them, and collect: 您可以流式传输每个列表,对其distinct进行应用并收集:

List<Integer> result = 
    Stream.concat(listA.stream(), listB.stream())
          .distinct()
          .collect(Collectors.toList());

You should use also like this ; 您也应该这样使用;

Stream<Integer> streamOfServiceMapIds = listA.stream().map(ServiceMap::getSeviceId);
List<ServiceMap> collectedList = Stream.concat(streamOfServiceMapIds, listB.stream())
        .distinct()
        .map(ServiceMap::new)
        .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM