Intersection of two lists of different objects in java

I have two Pojo classes with another field with a unique identifier.

I want to intersect two List<A> and List<B> .

What is the best thing to do. One of them - I can just repeat it twice, but then the complexity is too high n2.

is the best way to do this? Can I do this using a comparator?

 Class A { Id, Name ,DOB} Class B{ id, aid ,location } 

I have list A and list B

now want to get list A with location in B

+7
source share
5 answers

Apache Commons Collections has a way to do this: CollectionUtils.intersection . However, he does not use generics.

There is also this SO question: List intersection in java

+3
source

You can put the List<B> elements in the HashMap<Integer,B> , and the id key is.

Having done this, you can iterate over the List<A> elements and quickly search for the corresponding B elements using a hash map. This will provide the required structure ("list A with location in B ").

+2
source
  • Sort the list in ascending order of Id.

  • Start with List A and find the corresponding index in List B. Current Index Liste List of List B. say (indB)

  • Start with the following index on list A and compare on list B, starting at (indB + 1)

  • repeat from step 1 to 4 until list A ends OR OR list B ends.

+2
source

Try the following:

 public static void main(String[] args) {System.nanoTime() List<A> as = new ArrayList<A>(); List<B> bs = new ArrayList<B>(); // Collect all A.ids in the list of B into a Set Set<String> baids = new HashSet<String>(); for (B b : bs) baids.add(b.aid); // iterate through the list of A discarding those that don't have a B for (Iterator<A> i = as.iterator(); i.hasNext();) if (!baids.contains(i.next().Id)) // contains() executes fast for a Set i.remove(); // now list "as" contains all A that have a B with A.Id = B.aid } 
+1
source

Using Java 8 threads

 List<A> listA = new ArrayList<A>(); List<B> listB = new ArrayList<B>(); Set<Integer> aIdsFromBList = listB.stream().map(B::getAId).collect(Collectors.toSet()); return listA.stream .filter(a -> aIdsFromBList.contains(a.getId())) .collect(Collectors.toList()); 
0
source

All Articles