Java合并两个集合并去重
项目需求:
对两个List集合进行合并,并根据其对象的Id进行去重
Java实现:
假设两个集合为学生集合,根据学号Id进行去重合并
public List<Student> mergeList(List<Student> firstList, List<Student> secondList) {
List<Student> students = Lists.newArrayList();
// 创建Set存储Id保证不重复
Set<Long> ids = new HashSet<>();
// 将 firstList 中的元素添加到 mergedList 中,并记录其 id
for (Student item: firstList) {
if (ids.add(student.getId())){
students.add(item);
}
}
// 将secondList 中的元素添加到 mergedList 中,并记录其 id
for (Student student: secondList) {
if (ids.add(student.getId())) {
students.add(item);
}
}
return students;
}
还没有评论,来说两句吧...