作者:goodluckwj\来源:blog.csdn.net/qq_35634181/article/details/108867857ExportTemperatureDto实体对象:@Getter@Setter@ToStringpublicclassExportTemperatureDto{privateStringname;私人双早温度;私人双下午温度;私有字符串类ID;私有字符串gradeId;privateIntegerpersonId;}在一个ExportTemperatureDto的集合中,根据personId的属性去重生成一个新的集合。导入静态java.util.Comparator.comparing;导入静态java.util.stream.Collectors.collectionAndThen;导入静态java.util.stream.Collectors.toCollection;公共类StreamTest{publicstaticvoidmain(String[]args){ListtemperatureList=Lists.newArrayList();temperatureList.add(newExportTemperatureDto(1,"哈哈"));temperatureList.add(newExportTemperatureDto(2,"哈哈"));temperatureList.add(newExportTemperatureDto(3,"哈哈"));temperatureList.add(newExportTemperatureDto(4,"哈哈"));temperatureList.add(newExportTemperatureDto(1,"hahaasdas"));temperatureList.add(newExportTemperatureDto(2,"hahaasdas"));List结果=temperatureList.stream().collect(collectingAndThen(toCollection(()->newTreeSet<>(比较(ExportTemperatureDto::getPersonId))),ArrayList::new));结果.forEach(System.out::println);/*输出结果为:personId为1,其名称为哈哈personId为2,其名称为哈哈是因为TreeSet底层是通过TreeMap实现的,传入了基于getPersonId进行比较的comparator.当判断personId相同时,比较结果为0,然后将其值替换为value,但key值不会改变,并且由于TreeSet使用传入的元素作为key,所以在使用TreeSet时,当比较器的比较结果相同时,不会将原来的值替换为被比较的值*/}}知其然,知其所以然,这个流的操作好像有点难度,这里是一条记录,collectingAndThen根据属性完成去重操作,去重操作的关键是使用collectingAndThen,toCollection和TreeSet有点难理解。我当时也很困惑。我就记录在这里,以后一定会用到的。理解基于对象属性的去重,核心就是把集合放在TreeSet中,然后将TreeSet转为List,其中TreeSet需要传入一个comparator,根据哪个属性进行比较,然后使用publicArrayList(Collectionc)将TreeSet放入构造函数生成List。上面的Stream操作可以使用普通集合:TreeSettreeSet=newTreeSet<>(Comparator.comparing(ExportTemperatureDto::getPersonId));for(ExportTemperatureDtotemperatureDto:temperatureList){treeSet.add(temperatureDto);}Listresult2=newArrayList<>(treeSet);只要你能理解普通集合是如何操作的,那么在使用Stream流操作时,就看你是否熟悉API的使用了。其实这才是关键,只有了解了collectingAndThen,toCollection,JDK8的匿名函数才能看懂这个公式。这里简单介绍一下:首先说一下collectingAndThen方法的使用--------先收集结果集,然后在下一步处理收集到的结果集。红色的两句是理解collectingAndThen的关键,先看看collectingAndThen需要传递的参数:publicstaticCollectorcollectingAndThen(Collector下游,Functionfinisher)可以看到第一个参数是Collector接口的子类,所以对于Collector的处理,几乎都是toList()、toSet()、joining()等方法,Collectors工具类中的mapping()、collectingAndThen()都可以使用,所以感觉这个collectingAndThen很强大,可以嵌套使用。第二个参数是一个Function函数。熟悉的同学都知道Function函数是这样的:Rapply(Tt),这也是理解上面去重公式的关键。我以为是通过ArrayList::new调用的不带参数的构造方法,其实他调用的是带参数的ArrayList构造方法,publicArrayList(Collectionc)调用的是上面的构造方法,所以很清楚,就是第一个参数downstream的结果,到第二个参数Function函数的参数,Rapply(Tt),也就是把结果设置为t。因为toCollection是转换为集合的通用操作。当然,Collectors类中也有toList()和toSet()方法,但是他们并不满足于使用TreeSet收集集合的方法,所以使用toCollection是一个通用的方法。使用TreeSet收集,然后根据比较哪个属性传入comparator,这样就可以了。近期热点文章推荐:1.1000+Java面试题及答案(2022最新版)2.厉害了!Java协程来了。..3.SpringBoot2.x教程,太全面了!4.不要用爆破爆满画面,试试装饰者模式,这才是优雅的方式!!5.《Java开发手册(嵩山版)》最新发布,赶快下载吧!感觉不错,别忘了点赞+转发!