Remove duplicates from ArrayLists

后端 未结 14 2177
孤街浪徒
孤街浪徒 2020-11-27 04:12

I have an ArrayList of custom objects. I want to remove duplicate entries.

The objects have three fields: title, subtitle, and id. If a su

相关标签:
14条回答
  • 2020-11-27 04:58

    The solution depends on circumstances.

    If you don't have much data then go with a Set Set<T> unique = new HashSet<>(yourList); (use LinkedHashSet if you care about the order. It creates a new collection, but usually it's not a problem.

    When you want to modify existing list and don't want to/can't create a new collection, you can remove duplicates like here:

    List<Integer> numbers =
        new ArrayList<>(asList(1, 1, 2, 1, 2, 3, 5));
    
    System.out.println("Numbers: " + numbers);
    ListIterator<Integer> it = numbers.listIterator();
    while (it.hasNext()) {
        int i = it.nextIndex();
        Integer current = it.next();
        for (int j = 0; j < i; ++j) {
            if (current.equals(numbers.get(j))) {
                it.remove();
                break;
            }
        }
    }
    System.out.println("Unique: " + numbers);
    

    It works in O(n^2), but it works. Similar implementation, but simpler, is when the list is sorted - works in O(n) time. Both implementations are explained at Farenda: remove duplicates from list - various implementations.

    0 讨论(0)
  • 2020-11-27 05:02
    List list = (...);
    
    //list may contain duplicates.
    
    //remove duplicates if any
    Set setItems = new LinkedHashSet(list);
    list.clear();
    list.addAll(setItems);
    

    You may need to override "equals()" so that 2 elements are considered equals if they have the same subtitle (or tite and subtitle maybe ?)

    0 讨论(0)
提交回复
热议问题