方法如下:
//根據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());