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

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.


The same with Guava:

Set<String> combinedSet = Sets.union(oldStringSet, newStringSet)

You can do it using this one-liner

Set<String> combined = Stream.concat(newStringSet.stream(), oldStringSet.stream())
        .collect(Collectors.toSet());

With a static import it looks even nicer

Set<String> combined = concat(newStringSet.stream(), oldStringSet.stream())
        .collect(toSet());

Another way is to use flatMap method:

Set<String> combined = Stream.of(newStringSet, oldStringSet).flatMap(Set::stream)
        .collect(toSet());

Also any collection could easily be combined with a single element

Set<String> combined = concat(newStringSet.stream(), Stream.of(singleValue))
        .collect(toSet());

Tags:

Java

Set