[英]There has got to be a better way to count duplicates in a LinkedList
[英]A better way to dedupe when adding linkedlist to a linkedlist?
我正在嘗試向LinkedList添加一些重復數據刪除邏輯。 重復項來自新的LinkedList,這些新的LinkedList被添加到主LinkedList中。
masterList.addAll(0, newList)
對我來說,棘手的是,每個新列表都被添加到主列表的開頭(如上面的代碼所示)。 並且重復數據刪除需要保留以后添加的元素。 例如:
masterList = [3, 4]
newList = [5, 4]
masterList.addAll(0, newList)
現在masterList = [5, 4, 3, 4]
。 並且應將masterList末尾的“ 4”作為重復項刪除,而需要保留后面添加的“ 4”。 因此,重復數據刪除結果應為masterList = [5, 4, 3]
。
我當前的解決方案是在“添加”完成后刪除重復數據:
protected List<String> dedupeIds(List<String> masterList) {
// HashSet to store seen values
HashSet<String> set = new HashSet<>();
for (Iterator<String> iter = masterList.iterator(); iter.hasNext();) {
String doc_id = iter.next();
// put the doc id in Set hs, if cannot add as key, it means dupe
if (!set.add(doc_id)) {
iter.remove();
}
}
return masterList;
}
當前的解決方案有效,但是我想知道在“添加”期間是否有一種重復數據刪除方法?
正如Chrylis所建議的那樣,也許考慮使用其他收集類型。 LinkedHashSet
是存儲唯一元素(這是Set
)同時保留順序的一個不錯的選擇。
final Set<Integer> a = new LinkedHashSet<>(Arrays.asList(3, 4));
System.out.println(Arrays.toString(a.toArray())); // Prints [3, 4]
final Set<Integer> b = new LinkedHashSet<>(Arrays.asList(5, 4));
System.out.println(Arrays.toString(b.toArray())); // Prints [5, 4]
b.addAll(a);
System.out.println(Arrays.toString(b.toArray())); // Prints [5, 4, 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.