JAVA 对象整体去重+按照对象内某个属性去重
创始人
2024-03-15 22:15:22

 

目录

1 根据对象中的某一个属性去重

前置知识

---TreeSet---

-----Comparator.comparing ----

2对象整体去重


1 根据对象中的某一个属性去重

前置知识

---TreeSet---


TreeSet是一个有序集合,它扩展了AbstractSet类并实现了NavigableSet接口。

有以下特点

1 它存储唯一的元素
2 它不保留元素的插入顺序
3 它按升序对元素进行排序
4 它不是线程安全的
在实现中,对象根据其自然顺序以升序排序和存储。该TreeSet中使用平衡树。

常用API

TreeSet add
TreeSet contains
TreeSet remove
TreeSet clear
TreeSet size
TreeSet isEmpty 
TreeSet iterator
TreeSet first
TreeSet last 
TreeSet subSet
TreeSet headSet

具体看

Java TreeSet - Java教程 - 菜鸟教程 (cainiaojc.com)

常用在对象元素排序中

-----Comparator.comparing ----

comparing是比较器功能接口的静态方法。

Comparator.comparing方法在Java 8中被引入。

Comparator.comparing接受一个函数,该函数从给定类型中提取一个可比较的排序键(lambda形式的键),并返回一个通过该排序键进行比较的比较器。

思路:
先使用Comparator.comparing 对对象元素排序,然后将返回的迭代器对象给TreeSet,进行去重操作

代码

    public static List toDistinctList(List list) {//标签对象,根据标签名去除重复值Set Set1 = new TreeSet<>(Comparator.comparing(Category::getCategoryName));Set1.addAll(list);list.clear();list.addAll(Set1);return list;}

测试

    @Testpublic void toDistinctList() {List list=new ArrayList<>();list.add(new Category(1L,"JAVA","s4c",""));list.add(new Category(1L,"JAVA","4sc",""));list.add(new Category(1L,"C","sc2",""));list.add(new Category(1L,"C","sc1",""));list.add(new Category(1L,"A","s5c",""));List categories = AdminBlogBo.toDistinctList(list);System.out.println(categories);}

2对象整体去重

也是使用java8的新特性

    public static List toDistinctList(List list) {list = list.stream().distinct().collect(Collectors.toList());return list;

测试

    @Testpublic void toDistinctList() {List list=new ArrayList<>();list.add(new Category(1L,"JAVA","4sc",""));list.add(new Category(1L,"JAVA","4sc",""));list.add(new Category(1L,"C","4sc",""));list.add(new Category(1L,"C","4sc",""));list.add(new Category(1L,"A","s5c",""));List categories = AdminBlogBo.toDistinctList(list);System.out.println(categories);}

结果

[Category(categoryId=1, categoryName=JAVA, categoryDescription=4sc, categoryIcon=), Category(categoryId=1, categoryName=C, categoryDescription=4sc, categoryIcon=), Category(categoryId=1, categoryName=A, categoryDescription=s5c, categoryIcon=)]
 

相关内容

热门资讯

22日北京部分地区有小雪,未来... (来源:千龙网)新京报讯 据“气象北京”微信公众号消息,今天(12月21日)冬至,是北半球一年中黑夜...
最新!美军已派出F-35战机 据美国“战区”网站20日报道,美国对委内瑞拉加紧施压之际,美军已向加勒比海地区派出F-35战机。美国...
跨年后无法补缴!2025年度养...   长沙晚报掌上长沙12月21日讯(全媒体记者 刘攀)记者今日从长沙市人力资源和社会保障局获悉,按照...
智者勇进•接续奋进新江苏|江苏... 转自:扬子晚报作为一所国家级重点职业高级中学、国家中等职业教育改革发展示范学校、江苏省中等职业学校领...
奥尔特曼最新预测:未来告别屏幕... OpenAI的AI硬件计划备受关注,就在近日的一场播客中,被问及在筹备的AI硬件时,OpenAI C...