您在询问:
如何固定比较器,使其始终根据ID删除重复项,并根据值(升序)然后ID(降序)对有序集进行排序?
您想要比较器
>根据Obj.id删除重复项
>按Obj.alue和Obj.id对集合进行排序
要求1)导致
Function byId = o -> o.id;
Set setById = new TreeSet<>(Comparator.comparing(byId));
要求2)导致
Function byValue = o -> o.value;
Comparator sortingComparator = Comparator.comparing(byValue).thenComparing(Comparator.comparing(byId).reversed());
Set setByValueAndId = new TreeSet<>(sortingComparator);
让我们看一下TreeSet的JavaDoc.它说:
Note that the ordering maintained by a set […] must be consistent with equals if it is to
correctly implement the Set interface. This is so
because the Set interface is defined in terms of the equals operation,
but a TreeSet instance performs all element comparisons using its
compareTo (or compare) method, so two ele