[英]Java 8: Compare elements in Arraylist
我有一个ArrayList
的学生 :
如何有效地比较列表中的所有元素,以确保没有两个元素具有相同的ssn
或lName
值?
ArrayList<Student> students = getStudents();
public class Student {
private String id;
private String fName;
private String lName;
private String ssn;
}
您需要在Student类中重写equals()和hashcode()方法,以用于Stream API的distinct()方法。
students.stream().distinct().collect(Collectors.toList());
您可以构建一个键为ssn
的映射。 如果Collectors.toMap
遇到重复项,则将抛出IllegalStateException
students
.stream()
.collect(Collectors.toMap(Student::getSsn, Function.identity()));
或者您可以在合并功能中处理它
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.
}));
上面的内容可以帮助您识别重复项,但是您没有提到此后的操作。
编辑 (基于对问题的更新):
..但我也要确保lName值也是唯一的
您可以执行两次以上操作-一次用于SSN,一次用于姓氏。
或者,您可以覆盖equals
和hashCode
,如其他答案所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.