简体   繁体   中英

intersection of two list of different object in java

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

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

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 ").

  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.

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 
}

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM