您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
list 按照元素的某个字段去重
@Data @AllArgsConstructor @NoArgsConstructor public class Student { private Integer age; private String name; }
测试数据
List<Student> studentList = Lists.newArrayList(); studentList.add(new Student(28, "river")); studentList.add(new Student(12, "lucy")); studentList.add(new Student(33, "frank")); studentList.add(new Student(33, "lucy"));
java8 通过tree set 去重
List<Student> studentDistinctList = studentList.stream() .collect(Collectors.collectingAndThen (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(t -> t.getName()))), ArrayList::new ) ); System.out.println(new Gson().toJson(studentDistinctList));
扩展distinct 方法去重
List<Student> studentDistinct2List = studentList.stream().filter(StreamUtil.distinctByKey(t->t.getName())) .collect(Collectors.toList()); System.out.println(new Gson().toJson(studentDistinct2List));
工具类
public class StreamUtil { /** * https://stackoverflow.com/questions/23699371/java-8-distinct-by-property * @param keyExtractor * @param <T> * @return */ public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。