Calculating the intersection of two Java sets


This is my simple stupid Java tip for the day: to nondestructively calculate the intersection of two Set’s (ie, retain both object), do the following:

Set intersection = new HashSet(s1);
intersection.retainAll(s2);

Taken from Java Tutorials. Lessons learned: before implementing code which even vaguely seems that it should already exists, check with your favorite search engine. Also, who comes up with these function names? 🙂


3 responses to “Calculating the intersection of two Java sets”

  1. " …before implementing code which even vaguely seems that it should already exists, check with your favorite search engine." Exactly what I did. Thanks, dude!

  2. Yes! Thanks!
    The name is weird, but assuming that there should be some tool for intersection and given that all other methods are NOT this tool, retailAll should be it =)

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *