我正在编写代码以遍历多个列表,并使用Java 8 lambda表达式合并两个列表中的唯一值来创建另一个列表。
模型类:
class ServiceMap{
Integer serviceMapId;
Integer seviceId;
}
代码逻辑:
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));
使用Java Lambda表达式编写代码是否有效?
答案 0 :(得分:3)
您可以流式传输每个列表,将distinct
应用于它们,然后收集:
List<Integer> result =
Stream.concat(listA.stream(), listB.stream())
.distinct()
.collect(Collectors.toList());
答案 1 :(得分:3)
您也应该这样使用
Stream<Integer> streamOfServiceMapIds = listA.stream().map(ServiceMap::getSeviceId);
List<ServiceMap> collectedList = Stream.concat(streamOfServiceMapIds, listB.stream())
.distinct()
.map(ServiceMap::new)
.collect(Collectors.toList());