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
- 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.
- 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.
- To find the intersection, all we do is call retainAll(Collection c) passing in the collection to be compared.
- Then we print out the intersection results.
- 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?