Removing duplicate elements from a List

后端 未结 8 1584
忘掉有多难
忘掉有多难 2020-12-01 17:17

I have developed an array list.

ArrayList list = new ArrayList();

list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.add(\"         


        
8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 18:06

    You can convert to a Set with:

    Set aSet = new HashSet(list);
    

    Or you can convert to a set and back to a list with:

    list = new ArrayList(new HashSet(list));
    

    Both of these, however, are not likely to preserve the order of the elements. To preserve order, you can use a HashSet as an auxiliary structure while iterating:

    List list2 = new ArrayList();
    HashSet lookup = new HashSet();
    for (String item : list) {
        if (lookup.add(item)) {
            // Set.add returns false if item is already in the set
            list2.add(item);
        }
    }
    list = list2;
    

    In the case of duplicates, only the first occurrence will appear in the result. If you want only the last occurrence to appear, that's a tougher problem. I'd tackle it by reversing the input list, applying the above, and then reversing the result.

提交回复
热议问题