Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intersection of two list of different object in java

Tags:

java

algorithm

I have two Pojo Classes on with different field with unique ID.

I want to perform intersection of two List<A> and List<B> .

What is best way to do. One is i can simply iterate twice and but then the complexity is too high n2.

is any better way to do that ? Can i Do it with Comparator?

Class A {
Id, Name ,DOB}

Class B{
id, aid ,location }

I have list of A , and List of B

now want to get list of A with location in B

like image 226
Zuned Ahmed Avatar asked Jan 17 '12 07:01

Zuned Ahmed


2 Answers

Apache Commons Collections has a method to do this: CollectionUtils.intersection. It doesn't use generics, however.

There is also this SO question: List intersection in java

like image 113
Paul Avatar answered Nov 15 '22 19:11

Paul


  1. Sort both the list in increasing order of Id.

  2. Start with List A, and find corresponding index in List B. Remeber current index of List B. say (indB)

  3. Start with next index of List A, and compare in List B starting from (indB+1)

  4. repeat from step 1 to 4, until either List A is ended OR List B is ended.

like image 36
Azodious Avatar answered Nov 15 '22 21:11

Azodious