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

 

目录

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=)]
 

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...