stream 对象去重

2025-05-18 11:39:02

1、创建dto:@Setter@Getterpublic class StreamDto { private String uuid ; private String name; public StreamDto(String uuid, String name){ this.uuid = uuid; this.name = name; }}

2、创建工具类:public class StreamUtils { /** * 对象喉哆碓飙去重 * @param stringList */ public static List<StreamDto> removeDuplicate(List<StreamDto> stringList){ List<StreamDto> uniqueByNameAndSex = stringList.stream().collect( Collectors. collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getUuid() + ";" + o.getName()))), ArrayList::new)); return uniqueByNameAndSex; }}

3、测试案例:public class TestStream { @Test publi罕铞泱殳c void r髫潋啜缅emoveDuplicate(){ List<StreamDto> stringList = new ArrayList<>(); stringList.add(new StreamDto("abc","张三")); stringList.add(new StreamDto("cdf","李四")); stringList.add(new StreamDto("abc","张三")); List<StreamDto> streamDtoList = StreamUtils.removeDuplicate(stringList); streamDtoList.stream().forEach(streamDto -> System.out.println(streamDto.getUuid() + ";" + streamDto.getName())); }}

4、运行结果:abc;张三cdf;李四Process finished with exit code 0

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢