Back to Top

Friday, November 14, 2008

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 comments:

  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!

    ReplyDelete
  2. Anonymous9:33 PM

    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 =)

    ReplyDelete
  3. Anonymous2:46 PM

    saved me the complex logic of loop within a loop :) Thanks

    ReplyDelete