ArrayList of objects, compare objects and find duplicates, add object to new ArrayList only once for each duplicate

Viewed 600

Ive figured out how to compare the two ArrayLists and add the duplicates to a new 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);
            }
        }
    }

However done the way i do it, i add each duplicate once for everytime its there. Since "Rodaba" is there 7 times as she has 7 different priorities, she gets added to the list 7*6 times. Heres how i print out:

    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());
        }
    }

Is there a clever way i can avoid this, and only add "Rodaba" once for each priority she has applied for? Heres my output, is there a way to only get the marked section? Heres my output, is there a way to only get the marked section

I've been stuck on this for a long time. I'd really appreciate both suggestions on a better way to make the ArrayLists, as well as how to figure out this problem.

2 Answers
Related