【发布时间】:2021-07-21 17:54:02
【问题描述】:
我正在尝试从基于多个属性的学生对象列表中删除重复项,同时保留顺序,如下所示,我有一个学生对象列表,其中我们有多个同名且出勤率不同的学生...我需要删除同名且 studentAttendence 为 100 的重复学生,同时保留顺序。
Student{studentId=1, studentName='Sam', studentAttendence=100, studentAddress='New York'}
Student{studentId=2, studentName='Sam', studentAttendence=50, studentAddress='New York'}
Student{studentId=3, studentName='Sam', studentAttendence=60, studentAddress='New York'}
Student{studentId=4, studentName='Nathan', studentAttendence=40, studentAddress='LA'}
Student{studentId=5, studentName='Ronan', studentAttendence=100, studentAddress='Atlanta'}
Student{studentId=6, studentName='Nathan', studentAttendence=100, studentAddress='LA'}
去除重复后的输出:
Student{studentId=2, studentName='Sam', studentAttendence=50, studentAddress='New York'}
Student{studentId=3, studentName='Sam', studentAttendence=60, studentAddress='New York'}
Student{studentId=4, studentName='Nathan', studentAttendence=40, studentAddress='LA'}
Student{studentId=5, studentName='Ronan', studentAttendence=100, studentAddress='Atlanta'}
我现在只根据名称删除重复项,而不考虑百分比(100)......也没有保留订单......非常感谢任何帮助。(学生供应商是一个简单的供应商功能学生名单)
studentsSupplier.get().stream()
.sorted(Comparator.comparing(Student::getStudentName))
.collect(Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Student::getStudentName))), ArrayList::new));
注意:只有学生姓名匹配且百分比为 100 的重复记录必须删除,(记录 Ronon 的百分比为 100 但没有相同学生姓名的重复记录,因此不能删除)
【问题讨论】:
-
问题不清楚。考虑添加更多案例,例如出勤率仅为 100% 的学生。
-
必须通过Stream的处理来处理?
-
最简单的方法是覆盖等号和哈希码,你只需要
LinkedHashSet,那么它就是List<Student> filteredStudents = new LinkedList<>(new LinkedHashSet<>(students));。很好很简单。如果没有正确的等号和哈希码,您不能使用集合来删除重复项,在您的情况下,应该按姓名和出勤率构建。 -
studentId在整个表(或此输入列表)中是否唯一?
标签: java collections java-8 duplicates java-stream