簡體   English   中英

有沒有更好的方法在java中組合兩個字符串集?

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

我需要在過濾掉冗余信息的同時組合兩個字符串集,這是我想出的解決方案,有沒有人可以提出更好的方法? 也許我忽略了一些內置的東西? 谷歌沒有任何運氣。

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

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

由於Set不包含重復條目,因此您可以通過以下方式將兩者結合起來:

newStringSet.addAll(oldStringSet);

如果您添加兩次內容並不重要,該集合將只包含該元素一次...例如,無需使用contains方法進行檢查。

你可以使用這個單線來做到這一點

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());

番石榴相同:

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

從定義 Set 只包含唯一元素。

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;
}

如果您使用 Guava,您還可以使用構建器來獲得更大的靈活性:

ImmutableSet.<String>builder().addAll(someSet)
                              .addAll(anotherSet)
                              .add("A single string")
                              .build();

只需使用newStringSet.addAll(oldStringSet) 無需檢查重復項,因為Set實現已經這樣做了。

如果您使用的是 Apache Common,請使用org.apache.commons.collections4.SetUtils; SetUtilsorg.apache.commons.collections4.SetUtils;

SetUtils.union(setA, setB);

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

由於集合不能有重復項,只需將一個的所有元素添加到另一個即可生成兩者的正確並集。

 newStringSet.addAll(oldStringSet);

這將產生 s1 和 s2 的聯合

如果你關心性能,並且如果你不需要保留你的兩個集合並且其中一個可能很大,我建議檢查哪個集合是最大的並從最小的開始添加元素。

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

Set<String> myResult;
if(oldStringSet.size() > newStringSet.size()){
    oldStringSet.addAll(newStringSet);
    myResult = oldStringSet;
} else{
    newStringSet.addAll(oldStringSet);
    myResult = newStringSet;
}

這樣,如果您的新集合有 10 個元素,而舊集合有 100 000 個元素,則您只需執行 10 次操作而不是 100 000。

Set.addAll()

如果指定集合中的所有元素尚不存在,則將其添加到此集合中(可選操作)。 如果指定的集合也是一個集合,addAll 操作會有效地修改這個集合,使其值為兩個集合的並集

newStringSet.addAll(oldStringSet)

使用boolean addAll(Collection<? extends E> c)
如果指定集合中的所有元素尚不存在,則將其添加到此集合中(可選操作)。 如果指定的集合也是一個集合,addAll 操作會有效地修改這個集合,使其值是兩個集合的並集。 如果在操作進行時修改了指定的集合,則此操作的行為未定義。

newStringSet.addAll(oldStringSet)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM