Is there a better way to combine two string sets in java?

FooBar picture FooBar · Jan 30, 2012 · Viewed 82.1k times · Source

I need to combine two string sets while filtering out redundant information, this is the solution I came up with, is there a better way that anyone can suggest? Perhaps something built in that I overlooked? Didn't have any luck with google.

Set<String> oldStringSet = getOldStringSet();
Set<String> newStringSet = getNewStringSet();

for(String currentString : oldStringSet)
{
    if (!newStringSet.contains(currentString))
    {
        newStringSet.add(currentString);
    }
}

Answer

dacwe picture dacwe · Jan 30, 2012

Since a Set does not contain duplicate entries, you can therefore combine the two by:

newStringSet.addAll(oldStringSet);

It does not matter if you add things twice, the set will only contain the element once... e.g it's no need to check using contains method.