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