Java 8 Lambda - Intersection of Two Lists
The simplest approach is this:
List<T> intersect = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());
I need to compare them on assume list1.id == list2.fk_id
First build up a set of the fk_id;
Set<Integer> orderLineEntrSet = orderEntry.getOrderReleases().stream()
.flatMap(orderReleaseEntry ->
orderReleaseEntry.getOrderLines().stream())
.filter(orderLineEntry -> {
String s = orderLineEntry.getStatus();
return "PP".equals(s) || "PD".equals(s);
})
.map(e -> e.getId())
.collect(Collectors.toSet());
double[] totalAmount = { 0.0 };
double[] couponDiscount = { 0.0 };
orderLineEntryList.stream()
.flatMap(sre -> sre.getLineEntries().stream())
.filter(ole -> orderLineEntrySet.contains(ole.getOrderLineId())
.filter(ole -> !"PX".equals(ole.getStatusCode()))
.forEach(ole -> {
totalAmount[0] += ole.getFinalAmount();
if (ole.getCouponDiscount() != null)
couponDiscount[0] += ole.getCouponDiscount();
});
You can avoid using a reference to an array object by using reduce function. e.g. see how Collectors.averagingDouble is implemented. But I find this more complicated.
Note: this is O(N) by using a set of ids rather than using a list of matching ids which would be O(N^2)