Java 8 Lambda - Intersection of Two Lists

Reddy picture Reddy · Jul 28, 2015 · Viewed 85k times · Source

I am trying to find intersection of two lists based on some condition and doing some steps. Couldn't find a way to do it (in learning stage) :)

Double totalAmount = 0.00d;
Double discount = 0.00d;


List<OrderLineEntry> orderLineEntryList = orderEntry.getOrderReleases().stream()
    .flatMap(orderReleaseEntry -> orderReleaseEntry.getOrderLines().stream())
    .filter(orderLineEntry -> orderLineEntry.getStatus().equals("PP") || orderLineEntry.getStatus().equals("PD"))
    .collect(Collectors.toList());

for (OrderLineEntry orderLineEntry : orderLineEntryList) {
    for (SplitLineEntry splitLineEntry : splitReleaseEntry.getLineEntries()) {
        if (splitLineEntry.getOrderLineId().equals(orderLineEntry.getId()) && splitLineEntry.getStatusCode() != "PX") {
            totalAmount += orderLineEntry.getFinalAmount();
            couponDiscount += orderLineEntry.getCouponDiscount() == null ? 0.00d : orderLineEntry.getCouponDiscount();
        }
    }
}

As you see, the logic is simple

Get All items from order based on some filter list and intersect with another list and do some stuff.

Answer

Silas Reinagel picture Silas Reinagel · Jul 28, 2015

The simplest approach is this:

List<T> intersect = list1.stream()
                         .filter(list2::contains)
                         .collect(Collectors.toList());