How do I remove repeated elements from ArrayList?

后端 未结 30 1577
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  清酒与你
    2020-11-21 06:45

    This is used for your Custom Objects list

       public List removeDuplicates(List list) {
        // Set set1 = new LinkedHashSet(list);
        Set set = new TreeSet(new Comparator() {
    
            @Override
            public int compare(Object o1, Object o2) {
                if (((Contact) o1).getId().equalsIgnoreCase(((Contact) o2).getId()) /*&&
                        ((Contact)o1).getName().equalsIgnoreCase(((Contact)o2).getName())*/) {
                    return 0;
                }
                return 1;
            }
        });
        set.addAll(list);
    
        final List newList = new ArrayList(set);
        return newList;
    }
    

提交回复
热议问题