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

后端 未结 12 1266
天涯浪人
天涯浪人 2020-12-05 01:41

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 som

相关标签:
12条回答
  • 2020-12-05 02:05

    If you are using Guava you can also use a builder to get more flexibility:

    ImmutableSet.<String>builder().addAll(someSet)
                                  .addAll(anotherSet)
                                  .add("A single string")
                                  .build();
    
    0 讨论(0)
  • 2020-12-05 02:06

    If you are using the Apache Common, use SetUtils class from org.apache.commons.collections4.SetUtils;

    SetUtils.union(setA, setB);
    
    0 讨论(0)
  • 2020-12-05 02:07

    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());
    
    0 讨论(0)
  • 2020-12-05 02:08

    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.

    0 讨论(0)
  • 2020-12-05 02:08

    Use boolean addAll(Collection<? extends E> c)
    Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

    newStringSet.addAll(oldStringSet)
    
    0 讨论(0)
  • 2020-12-05 02:09

    Just use newStringSet.addAll(oldStringSet). No need to check for duplicates as the Set implementation does this already.

    0 讨论(0)
提交回复
热议问题