Remove duplicates from ArrayLists

后端 未结 14 2180
孤街浪徒
孤街浪徒 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 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 numbers =
        new ArrayList<>(asList(1, 1, 2, 1, 2, 3, 5));
    
    System.out.println("Numbers: " + numbers);
    ListIterator 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.

提交回复
热议问题