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

后端 未结 12 1301
天涯浪人
天涯浪人 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:07

    You can do it using this one-liner

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

    With a static import it looks even nicer

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

    Another way is to use flatMap method:

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

    Also any collection could easily be combined with a single element

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

提交回复
热议问题