小猿圈Java老师给大家分享一篇关于如何实现Java8中list按照元素的某个字段去重的详细介绍,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,下面我们一起来看一下吧。
![strip](https://upload-images.jianshu.io/upload_images/15397392-39dada1d445c0053.jpg?imageMogr2/auto-orient/strip)
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通过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就到小猿圈去看看吧,里面有最全最新的课程等着你。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69933859/viewspace-2648396/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/69933859/viewspace-2648396/