Alex Rivera | Logout

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

Asked 2012-01-30T10:39:40.287
131

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);
    }
}
Edit
Report

1 Answer

3

http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#addAll(java.util.Collection)

Since sets can't have duplicates, just adding all the elements of one to the other generates the correct union of the two.

answered 2012-01-30T10:42:02.960

Your Answer