简体   繁体   中英

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.

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?

You could stream each list, apply distinct to them, and collect:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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