集合元素为对象时,根据对象中属性去重操作,如下所示:
List<User> list = Arrays.asList(new User(3,"张三"), new User(2,"李四"),new User(2,"王五"));
1.根据 用户年龄去重:
List<User> newDto = list.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing( u-> u.getAge()))), ArrayList::new) );
结果为:new User(3,"张三"), new User(2,"李四")。
2.根据用户年龄把重复值清空
注:清空的意思为只要为重复值就都去掉
List<User> newDto = list.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing( User :getAge()))), ArrayList::new) );
结果为:new User(3,"张三")。