List集合中根据某属性值是否重复去除元素(使用JDK8以上新特性)


方法如下:

//根据Student类的userId来移除相同的元素,即如果某元素的userId跟之前元素的userId重复了,就从List中移除

public List<Student> removeDuplicateUser(List<Student> students){ //Set可以保证不重复,TreeSet可以保证顺序不打乱 Set<Student> studentSet = new TreeSet<>(Comparator.comparing(Student::getUserId)); studentSet.addAll(students); return new ArrayList<>(studentSet); }

//list直接调用上面的方法即可
List<Student> notRepeatStudent = removeDuplicateUser(repeatStudent);

----------------------------------------------分割线-----------------------------------------------------------------

记录下使用JDK8以上新特性Stream流的方式去除List重复的元素,与上面的不同,这里是元素重复,上面是元素的属性值重复
List<Student> distinctstudents = student.stream().distinct().collect(Collectors.toList());


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM