Java - Distinct List of Objects

后端 未结 9 926
不知归路
不知归路 2020-12-05 09:41

I have a list/collection of objects that may or may not have the same property values. What\'s the easiest way to get a distinct list of the objects with equal properties? I

9条回答
  •  旧时难觅i
    2020-12-05 10:28

    Place them in a TreeSet which holds a custom Comparator, which checks the properties you need:

    SortedSet set = new TreeSet(new Comparator(){
    
        public int compare(MyObject o1, MyObject o2) {
             // return 0 if objects are equal in terms of your properties
        }
    });
    
    set.addAll(myList); // eliminate duplicates
    

提交回复
热议问题