簡體   English   中英

從大型集合中獲取重復項的最佳性能方式是什么<string> ?</string>

[英]What it is the best performance way to grab duplicates from a large Set<String>?

我有一個包含許多單詞的大型Set<String> ,例如:

“aaa, cCc, dDD, AAA, bbB, BBB, AaA, CCc, ...”

我想對 Set 中的所有重復單詞進行分組,忽略單詞的大小寫敏感性,然后將它們保存在Vector<Vector<String>>或其他任何內容中,因此每個Vector<String>項都將包含一組相似的單詞,如下所示:

Vector<String> : aaa, AAA, AaA, ...

Vector<String> : cCc, CCc, ...

Vector<String> : bbB, BBB, ...

我關心性能,因為這個 Set 包含很多單詞。

如果您真正關心性能,則不會使用Vector 至於排序問題,一種解決方案是使用TreeMapTreeSet object 並創建一個Comparator器來執行您想要的相等(排序)。

實例化可以是:

new TreeMap<String,LinkedList<String>>(new Comparator<String>() {

   // comparator here

});

用法:

LinkedList<String> entry = map.get(nextKey);
if (entry == null) {
  entry = new LinkedList<String>()
  map.put(nextKey, entry);
}
entry.add(nextKey);

我會創建一個HashMap<String, Vector<String>> hashMap 接下來,對於您的集合中的每個“字符串”

if (!hashMap.containsKey(string.toLowerCase()){
     Vector v = new Vector();
     v.add(string);
      hashMap.put(string.toLowerCase(), v);
} else { 
     hashMap.get(string.toLowerCase()).add(string);
}

最后,根據需要創建向量向量,或使用 hashmap.valueSet()

如果您可以選擇Set實現,則可以將TreeSetComparator一起使用,比較字符串忽略大小寫。 然后,您將能夠遍歷排序列表並輕松分組重復項。

這會迭代輸入集一次,我懷疑你能比這快得多。 ArrayList交換為LinkedLists可能會以局部性換取更少的復制,這可能會提高性能,但我對此表示懷疑。 這是代碼:

Set<String> input = new HashSet<String>(Arrays.asList(
    "aaa", "cCc", "dDD", "AAA", "bbB", "BBB", "AaA", "CCc"));

Map<String, List<String>> tmp = new HashMap<String, List<String>>();

for (String s : input) {
    String low = s.toLowerCase();
    List<String> l = tmp.get(low);

    if (l == null) {
        l = new ArrayList<String>();
        tmp.put(low, l);
    }

    l.add(s);
}

final List<List<String>> result = new ArrayList<List<String>>(tmp.values());

暫無
暫無

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

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