Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda - Intersection of Two Lists

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.

like image 807
RaceBase Avatar asked Jul 28 '15 17:07

RaceBase


People also ask

How to get intersection of 2 list in java?

Intersection of Two Lists of StringsList<String> list = Arrays. asList("red", "blue", "blue", "green", "red"); List<String> otherList = Arrays. asList("red", "green", "green", "yellow");

How do you find common elements in multiple lists?

You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.

How do you use intersection in Java?

intersection() returns an unmodifiable view of the intersection of two sets. The returned set contains all elements that are contained by both backing sets. The iteration order of the returned set matches that of set1. Return Value: This method returns an unmodifiable view of the intersection of two sets.


1 Answers

The simplest approach is this:

List<T> intersect = list1.stream()                          .filter(list2::contains)                          .collect(Collectors.toList()); 
like image 64
Silas Reinagel Avatar answered Sep 20 '22 00:09

Silas Reinagel