[英]Loop multiple different type of lists and create another using java 8 lambda expressions
[英]How 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表達式合並兩個列表中的唯一值來創建另一個列表。
型號類別:
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表達式編寫代碼是否有效?
您可以流式傳輸每個列表,對其distinct
進行應用並收集:
List<Integer> result =
Stream.concat(listA.stream(), listB.stream())
.distinct()
.collect(Collectors.toList());
您也應該這樣使用;
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.