简体   繁体   English

将链表添加到链表时,更好的重复数据删除方法?

[英]A better way to dedupe when adding linkedlist to a linkedlist?

I'm trying to add some dedupe logic to a LinkedList. 我正在尝试向LinkedList添加一些重复数据删除逻辑。 The duplicates come from new LinkedLists getting added to the master LinkedList.: 重复项来自新的LinkedList,这些新的LinkedList被添加到主LinkedList中。

masterList.addAll(0, newList)

The tricky part for me is that, each new list is getting added to the beginning of the master list (as the above code shows). 对我来说,棘手的是,每个新列表都被添加到主列表的开头(如上面的代码所示)。 And the dedupe needs to keep the elements that are added later. 并且重复数据删除需要保留以后添加的元素。 For instance: 例如:

masterList = [3, 4]
newList = [5, 4]
masterList.addAll(0, newList)

Now masterList = [5, 4, 3, 4] . 现在masterList = [5, 4, 3, 4] And the "4" at the end of masterList should be removed as dupe while the later-added "4" needs to remain. 并且应将masterList末尾的“ 4”作为重复项删除,而需要保留后面添加的“ 4”。 So the dedupe result should be masterList = [5, 4, 3] . 因此,重复数据删除结果应为masterList = [5, 4, 3]

My current solution is to dedupe AFTER the "add" is done: 我当前的解决方案是在“添加”完成后删除重复数据:

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

The current solution works, but I wonder if there is a way to dedupe during "add"? 当前的解决方案有效,但是我想知道在“添加”期间是否有一种重复数据删除方法?

As Chrylis suggested, perhaps consider a different collection type. 正如Chrylis所建议的那样,也许考虑使用其他收集类型。 LinkedHashSet would be a good choice for storing unique elements (it's a Set ) while also preserving order. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM