Java合并两个集合并去重

深碍√TFBOYSˉ_ 2023-10-08 23:03 90阅读 0赞

项目需求:
对两个List集合进行合并,并根据其对象的Id进行去重

Java实现:
假设两个集合为学生集合,根据学号Id进行去重合并

  1. public List<Student> mergeList(List<Student> firstList, List<Student> secondList) {
  2. List<Student> students = Lists.newArrayList();
  3. // 创建Set存储Id保证不重复
  4. Set<Long> ids = new HashSet<>();
  5. // 将 firstList 中的元素添加到 mergedList 中,并记录其 id
  6. for (Student item: firstList) {
  7. if (ids.add(student.getId())){
  8. students.add(item);
  9. }
  10. }
  11. // 将secondList 中的元素添加到 mergedList 中,并记录其 id
  12. for (Student student: secondList) {
  13. if (ids.add(student.getId())) {
  14. students.add(item);
  15. }
  16. }
  17. return students;
  18. }

发表评论

表情:
评论列表 (有 0 条评论,90人围观)

还没有评论,来说两句吧...

相关阅读

    相关 合并集合

    题目描述: 假设有两个集合 A 和 B 分别用两个线性表 LA 和 LB 表示,编写一个算法求一个新的集合C=A∪B,即将两个集合的并集放在线性表LC中。