Remove duplicates from ArrayLists

后端 未结 14 2231
孤街浪徒
孤街浪徒 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:47

    You can put the content of the ArrayList in a TreeSet using a custom Comparator which should return 0 if the two subtitles are the same. After that you can convert the Set in a List and have the List without "duplicates". Here is an example for Object, of course you should use the correct class and logic.

    public void removeDuplicates(List l) {
        // ... the list is already populated
        Set s = new TreeSet(new Comparator() {
    
            @Override
            public int compare(Object o1, Object o2) {
                // ... compare the two object according to your requirements
                return 0;
            }
        });
                s.addAll(l);
        List res = Arrays.asList(s.toArray());
    }
    
        

    提交回复
    热议问题