简体   繁体   English

Comparator.comparing 中的多项检查

[英]Multiple checks in Comparator.comparing

I have a list of objects, 'Students' - each 'Student' storing Name & Student ID.我有一个对象列表,“学生” - 每个“学生”存储姓名和学生 ID。 I want to sort the list in ascending order of their ID and also make sure that no two students have the same ID number.我想按他们的 ID 升序对列表进行排序,并确保没有两个学生具有相同的 ID 号。 If there are multiple students with same ID, throw an exception, else do something.如果有多个学生具有相同的 ID,则抛出异常,否则执行其他操作。

For sorting part, I am using a Comparator -对于排序部分,我使用的是比较器 -

students.sort((Comparator.comparing(Student::getStudentID).reversed()));

For the second part, I can add another for loop, iterate through students, and do the check.对于第二部分,我可以添加另一个 for 循环,遍历学生并进行检查。

I want to avoid the second loop and check for multiple IDs while I am sorting itself.我想避免第二个循环并在我自己排序时检查多个 ID。 Is there an efficient way to do this ?有没有一种有效的方法来做到这一点?

[Sorry if the question is too basic, I am trying to look for more efficient way of coding] [对不起,如果问题太基本,我正在尝试寻找更有效的编码方式]

You could write your own Comparator - ie:您可以编写自己的Comparator - 即:

class StudentsComparator implements Comparator<Student> {
    @Override
    public int compare(Student student1, Student student2) {
        if (student1.getStudentId().equals(student2.getStudentId())) {
            throw new IllegalStateException("Same ids");
        }

        return student2.getStudentId().compareTo(student1.getStudentId());
    }
}

then you could just do: students.sort(new StudentsComparator());那么你可以这样做: students.sort(new StudentsComparator()); to get the proper result.以获得正确的结果。

However, searching for the duplicates first and then sorting in another pass would probably be a cleaner solution, decoupling two different requirements from each other.然而,首先搜索重复项,然后在另一轮中排序可能是一个cleaner解决方案,将两个不同的要求相互分离。 Unless you really really care about performance, it's a better choice to do 2 runs - it is a cleaner code.除非您真的很关心性能,否则执行 2 次运行是更好的选择 - 这是一个更干净的代码。

UPDATE更新

As for finding duplicates, you could go in various directions.至于查找重复项,您可以朝各个方向进行。 One being:一种是:

private boolean hasDuplicates(List<Student> students) {
    return students.size() != students.stream().map(Student::getStudentId).distinct().count();
}

Here, for every student, you're getting his id (in the map method you're replacing student with his id), and then you're getting only distinct values.在这里,对于每个学生,您都获得了他的 id(在map方法中,您用他的 id 替换了 student),然后您只能获得不同的值。 If the number of distinct values is different from the size of the original list, then there are duplicates in the list.如果不同值的数量与原始列表的大小不同,则列表中存在重复项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM