小猿圈Java开发之list按照元素某个字段去重详解
小猿圈Java老师给大家分享一篇关于如何实现Java8中list按照元素的某个字段去重的详细介绍,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们一起来看一下吧。https://upload-images.jianshu.io/upload_images/15397392-39dada1d445c0053.jpg?imageMogr2/auto-orient/striplist按照元素的某个字段去重@Data@AllArgsConstructor@NoArgsConstructorpublic 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通过treeset去重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));}}以上就是小猿圈java讲师对于list按照元素某个字段去重详解的介绍,相信通过以上介绍你对于Java也是有了一定的了解,学习java是不断看视频看书不断进步的过程java自学交流群:743849624,需要一点点积累才能得到质的飞跃的,想学习Java就到小猿圈去看看吧,里面有最全最新的课程等着你。
页:
[1]