user1820620
user1820620

Reputation: 702

Java intersection Collection

I'd like to find an elegant way to this:

I have two collections A and B, if they both are not empty, then I need to do the intersection (store common elements in another list).

If one of them is empty I'll have to take all elements of the other.

If both are empty the resulting collection will be empty.

Is there a way to solve this problem without using many if conditions and with a good performance?

This is working but it's not so nice:

import org.apache.commons.collections4.CollectionUtils;
...
...
    List<Long> listA = new ArrayList<Long>();
    List<Long> listB = new ArrayList<Long>();
    //initialisation list A & listB

    List<Long> outputList = null;
    if(listA.size()>0 && listB.size() >0) {
        outputList = new ArrayList(CollectionUtils.intersection(listB, listA));
    }
    else if(listA.size()==0){
        outputList = listB;
    }
    else if(listB.size()==0){
        outputList = listA;
    }

Thank you!

Upvotes: 1

Views: 4927

Answers (2)

Caleb Jares
Caleb Jares

Reputation: 6307

I wouldn't imagine so, simply because of your condition:

If one list is empty, return the other list.

This is not a typical definition of intersection, and I'm not sure it is a common operation that would be covered in the standard library. As such, you'll have to handle that logic yourself.

If you'd really like to get rid of the if statements, then you can use the ternary operator:

return listA.isEmpty() ? listB :
       listB.isEmpty() ? listA :
       new ArrayList(CollectionUtils.intersection(listB, listA));

Upvotes: 2

janos
janos

Reputation: 124656

You have specific requirements for each possible combination of empty and nonempty input sets. It's only natural that you have several if statements to distinguish the cases and respond according to your requirements. There's no way around that.

But your solution can be improved a bit:

  • it's more idiomatic to use .isEmpty() instead of comparing size to 0
  • you forgot an else statement, and this the handling of the empty-empty case

Fixing these issues the code becomes:

final List<Long> outputList;
if (!listA.isEmpty() && !listB.isEmpty()) {
    outputList = new ArrayList(CollectionUtils.intersection(listB, listA));
}
else if (listA.isEmpty()) {
    outputList = listB;
}
else if (listB.isEmpty()) {
    outputList = listA;
} else {
    outputList = Collections.emptyList();
}

Upvotes: 1

Related Questions