I have two lists of ClassA
List<ClassA> list1;
List<ClassA> list2;
I want to create 4 lists:
List<ClassA> matchedList1;
List<ClassA> matchedList2;
List<ClassA> unmatchedList1;
List<ClassA> unmatchedList2;
where matchedList1 and matchedList2 contain in order items with same classA.name (unique)
unmatchedList1 and unmatchedList2 contain in order items that were not paired.
e.g.
list1 = name1, name2, name3
list2 = name4, name1, name3
matchedList1 = name1, name3 
matchedList2 = name1, name3 
unmatchedList1 = name2
unmatchedList2 = name4
is there any lambda expression to pair items from two lists according to some predicate?
                        
As you added the
lambdatag, I suppose that you are ok with Java-8 solution. Note that yourmatchedList1andunmatchedList1contain all the elements from thelist1, so you actually need to partition thelist1according to the predicate of having the same element inlist2. This can be done using thepartitioningBycollector:You can create
matchedList2andunmatchedList2exactly in the same way:Note that this solution is not very efficient: its complexity is
O(list1.size()*list2.size()). If you worry about the efficiency, it's better to build the sets of the names in both lists before.Alternatively if your lists are pre-sorted by the
namefield, you can use the binary search to speedup the procedure: