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?
Stream.of(listA, listB).map(Collection::stream).reduce(Stream.empty(), Stream::concat).distinct().collect(Collectors.toList()). Your solution is certainly not correct.Set<Integer> set = new HashSet<>(listA); listB.stream().filter(i -> !set.contains(i)).forEach(set::add);Stream.of(listA, listB) .map(List::stream) .reduce(Stream::concat) .orElse(Stream.empty()) .distinct() .collect(Collectors.toList());but, still, why notStream.concat(listA, listB)directly...