Reputation: 2002
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?
Upvotes: 0
Views: 742
Reputation: 2147
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());
Upvotes: 3
Reputation: 311393
You could stream each list, apply distinct
to them, and collect:
List<Integer> result =
Stream.concat(listA.stream(), listB.stream())
.distinct()
.collect(Collectors.toList());
Upvotes: 3