Friday, April 23, 2010

Finding Intersections Destructively / Nondestructively - Java Collections

What is an intersection?

Mathematical set theory states an intersection is the common elements between given sets. It's stated as such, A ∩ B, where A and B are different sets. 

Visually it looks like this: 

When would you need to calculate intersects?

Given n collections, you need to identify only the elements they have in common and ignore the rest.

Admittedly, I'm a bit spoiled coming from a web technology wherein most cases you can just write up some snazzy SQL to find the commonality and return the record set. In a good sized Java application though you'll often have a good amount of objects and data stored using collections in cache, so SQL is out of the question. You may be tempted to go down the road and create some sort of method that looks like so numberOfOccurrences(Set, String)that returns the number of occurrences and you use that number to determine what to drop and what to keep. This could work but there is a better, more efficient way to achieve this using a built in Java method - retainAll() that resides in the Collections interface. Lets see how:

The code

  1. We create two sets each holding fruits. You'll see that Apple and Orange are the common elements between the two sets. Make believe these two sets are your collections sitting in cache.
  2. We create an HashSet called intersection to hold our common values. Since we are created a holding set, we are finding the intersection nondestructively, which means without modifying the any of sets being compared. Simply instantiate the intersection set passing in set1 as the initializer.
  3. To find the intersection, all we do is call retainAll(Collection c) passing in the collection to be compared.
  4. Then we print out the intersection results.
  5. Next I show you how to destructively find the intersection by using set2 against set1, again using retainAll() and printing out the both sets. You'll see that set2 has been altered.
You should see the following results...

So, there you have it. Pretty painless right?

1 comment:

jackob said...

Fantastic! congratulations for your work and ideas.
ColdFusion Downloads