多语言展示
当前在线:429今日阅读:126今日分享:42

stream 对象去重

使用jdk1.8 新特性 使用stream 按属性去重
工具/原料
1

IDEA2019

2

java1.8

方法/步骤
1

创建dto:@Setter @Getter public 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 removeDuplicate(List stringList){         List 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     public void removeDuplicate(){         List stringList = new ArrayList<>();         stringList.add(new StreamDto('abc','张三'));         stringList.add(new StreamDto('cdf','李四'));         stringList.add(new StreamDto('abc','张三'));          List streamDtoList = StreamUtils.removeDuplicate(stringList);          streamDtoList.stream().forEach(streamDto -> System.out.println(streamDto.getUuid() + ';' + streamDto.getName()));     } }

4

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

推荐信息