不想重写对象的equals和hashcode方法,想直接通过new TreeSet(Comparator)进行对象去重,但发现去重不彻底
public class Comment {
private String dimensionKey;
private String dimensionValue;
private String indicatorsKey;
private String indicatorsValue;
}
List<Comment> comments = new ArrayList<>();
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("30").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("3").indicatorsKey("1").indicatorsValue("60").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("10").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("2").indicatorsKey("1").indicatorsValue("40").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("2").indicatorsKey("1").indicatorsValue("50").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("20").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("3").indicatorsKey("1").indicatorsValue("70").build());
comments.add(Comment.builder().dimensionKey("2020").dimensionValue("1").indicatorsKey("1").indicatorsValue("30").build());
TreeSet<Comment> set = new TreeSet<>((a, b) -> {
if (Objects.equals(a.getDimensionKey(), b.getDimensionKey()) &&
Objects.equals(a.getDimensionValue(), b.getDimensionValue()) &&
Objects.equals(a.getIndicatorsKey(), b.getIndicatorsKey())) {
return 0;
}
return 1;
});
set.addAll(comments);
很明显,是想利用dimensionKey+dimensionValue+indicatorsKey这三个属性的组合去重,根据我造的数据,最终结果只有3个才对,但实际上出现了四个。
下面是运行结果,可以看到2020.1.1没有去重彻底
你要想搞清楚这个问题,最好先了解TreeSet的底层实现,了解红黑树。
直接用stream流,一行代码搞定
通过new TreeSet(Comparator)去重也是要重写对象的equals和hashcode方法。
参考一下HashSet,如有帮助请采纳
https://blog.csdn.net/weixin_28836875/article/details/114520443
想一想treeset通过什么去重