对象的ArrayList,比较对象和查找重复项,每个重复

时间:2017-07-11 12:42:08

标签: java arraylist duplicates compare

我已经想出如何比较两个ArrayLists并将重复项添加到新的ArrayList。

    ArrayList<Student> allStudentsA = assignStudents();
    ArrayList<Student> allStudentsB = allStudentsA;

    for (Student studentA : allStudentsA) {
        for (Student studentB : allStudentsB) {
            if (studentA.getId().equals(studentB.getId()) && studentA.getEduNumber() != studentB.getEduNumber()) {
                duplicateStudents.add(studentB);
            }
        }
    }

然而按照我的方式完成,我每次都会在每次重复时添加一次。由于“Rodaba”有7次,因为她有7个不同的优先级,她被列入名单7 * 6次。以下是我如何打印出来的:

    for (Student student : duplicateStudents) {
        if (student.getFornavn().equals("Rodaba")) {
            System.out.println("Name: " + student.getFornavn() + "\t \t" + "EduNumber: " + student.getOptagelsesområde() + "\t" + "Prio: " + student.getPrio());
        }
    }

我是否有一种聪明的方法可以避免这种情况,并且只为她申请的每个优先级添加一次“Rodaba”? 继承我的输出,有没有办法只获得标记的部分? Heres my output, is there a way to only get the marked section

我已经坚持了很久。我非常感谢有关更好地制作ArrayLists的方法的建议,以及如何解决这个问题。

2 个答案:

答案 0 :(得分:3)

正如我在评论中指出的那样,你可以在添加之前检查一个学生是否存在:

ArrayList<Student> allStudentsA = assignStudents();
ArrayList<Student> allStudentsB = allStudentsA;

for (Student studentA : allStudentsA)
    for (Student studentB : allStudentsB)
        if (studentA.getId().equals(studentB.getId())
            && studentA.getEduNumber() != studentB.getEduNumber())
            if (!duplicateStudents.contains(studentB))
                duplicateStudents.add(studentB);

请注意,只有如果您覆盖equals类的hashCodeStudent方法,这只会有效,因为对象没有相同的引用

基本上,在添加Student之前,您将检查列表中是否已有equals。如果您正确实施了IntentService方法,则学生 A 将不等于具有不同优先级的A

答案 1 :(得分:1)

You can use a different approach with streams. Eg:

List<Student> allStudentsA = assignStudents();
List<Student> duplicateStudents = allStudents.stream()
    .collect(groupingBy(Student::getId)) 
//Now you've got Map<String, List<Student>> (assuming id is of type String).
//Id of an user is a key. In value (list) you have all Students with the same id.
//Now we want to take this lists which have size greater than two and merge them.
    .values()
    .stream()
    .filter(list -> list.size() >= 2)
    .flatMap(List::stream)
    .collect(Collectors.toList());

(Improvements are welcome.)