0

i have an ArrayList of students:
How can i efficiently compare all elements in the list to make sure no two elements have the same ssn or lName value?

ArrayList<Student> students = getStudents();

public class Student { 
    private String id;
    private String fName;
    private String lName;
    private String ssn;
}
NoobEditor
  • 15,563
  • 19
  • 81
  • 112
usr1234
  • 61
  • 2
  • 9
  • These are two separate questions, compare elements and make sure no duplicate ssn. Do you want a method like `containsDuplicateSSN`? – Shanu Gupta Jun 04 '18 at 04:42
  • actually, just need to ensure that there are no duplicate ssn, lName values – usr1234 Jun 04 '18 at 04:43
  • Are students store in database? – Shanu Gupta Jun 04 '18 at 04:44
  • Possible duplicate of [Remove duplicates from a list of objects based on property in Java 8](https://stackoverflow.com/questions/29670116/remove-duplicates-from-a-list-of-objects-based-on-property-in-java-8) – Amogh Jun 04 '18 at 04:47
  • @ShanuGupta no, the arrayList is user input – usr1234 Jun 04 '18 at 04:50
  • @ShanuGupta my function is called at the time the input is taken! – usr1234 Jun 04 '18 at 04:54
  • If you don't want duplicated value, simply use a `Set`, that will be easier. `new HashSet(list)`, note that this required `equals` and `hashcode` to be implemented correctly ! It doesn't required any java-8 features. – AxelH Jun 04 '18 at 06:11

2 Answers2

3

You need to override equals() and hashcode() methods in Student class for distinct() method of Stream API.

students.stream().distinct().collect(Collectors.toList());
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18
1

You can construct a map whose key is ssn. Here Collectors.toMap will throw IllegalStateException if it encounters duplicates

students
      .stream()
      .collect(Collectors.toMap(Student::getSsn, Function.identity()));

Or you could handle it in the merge function

students
        .stream()
        .collect(Collectors.toMap(Student::getSsn, Function.identity(), (student1, student2) -> {
                System.out.println(student1 + " and " + student2 + " had duplicate SSNs");
                return student1; //Just for demonstration I'm returning the first one.
            }));

The above will help you identify duplicates, but you haven't mentioned what to do after that.

EDIT (based on update to question):

.. but i need to ensure lName values are unique too

You could do the above twice - once for SSN and once for the last name.

Or you could override equals and hashCode as shown in the other answer.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79