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.