Reputation: 1387
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
Upvotes: 9
Views: 9176
Reputation: 4249
Using Java 8 streams
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());
Upvotes: 2
Reputation: 425003
Try this:
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
}
Upvotes: 1
Reputation: 500317
You could put elements of List<B>
into a HashMap<Integer,B>
, with the id
being the key.
Having done that, you can iterate over elements of List<A>
and quickly look up the corresponding B
elements using the hash map. That'll provide the structure you require ("list of A
with location in B
").
Upvotes: 2
Reputation: 13872
Sort both the list in increasing order of Id.
Start with List A, and find corresponding index in List B. Remeber current index of List B. say (indB)
Start with next index of List A, and compare in List B starting from (indB+1)
repeat from step 1 to 4, until either List A is ended OR List B is ended.
Upvotes: 2
Reputation: 20061
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
Upvotes: 3