有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

有没有更好的方法在java中组合两个字符串集?

我需要合并两个字符串集,同时过滤掉冗余信息,这是我提出的解决方案,有没有更好的方法可以推荐?也许是我忽略的内在因素?没有任何运气与谷歌

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

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

共 (6) 个答案

  1. # 1 楼答案

    Guava相同:

    Set<String> combinedSet = Sets.union(oldStringSet, newStringSet)
    
  2. # 2 楼答案

    只需使用newStringSet.addAll(oldStringSet)。无需检查重复项,因为Set实现已经这样做了

  3. # 3 楼答案

    如果您使用的是番石榴,您也可以使用生成器来获得更大的灵活性:

    ImmutableSet.<String>builder().addAll(someSet)
                                  .addAll(anotherSet)
                                  .add("A single string")
                                  .build();
    
  4. # 4 楼答案

    由于Set不包含重复条目,因此可以通过以下方式将两者结合起来:

    newStringSet.addAll(oldStringSet);
    

    添加两次并不重要,集合只包含一次元素。。。e、 g不需要使用contains方法进行检查

  5. # 5 楼答案

    定义集中的元素仅包含唯一的元素

    Set<String> distinct = new HashSet<String>(); 
     distinct.addAll(oldStringSet);
     distinct.addAll(newStringSet);
    

    为了增强代码,您可以为此创建一个通用方法

    public static <T> Set<T> distinct(Collection<T>... lists) {
        Set<T> distinct = new HashSet<T>();
    
        for(Collection<T> list : lists) {
            distinct.addAll(list);
        }
        return distinct;
    }
    
  6. # 6 楼答案

    你可以用这一行

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

    通过静态导入,它看起来更漂亮

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

    另一种方法是使用flatMap方法:

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

    此外,任何集合都可以轻松地与单个元素组合

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