比较两个列表并从中删除重复项

Comparing two lists and removing duplicates from one(比较两个列表并从中删除重复项)
本文介绍了比较两个列表并从中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个名为 FormObject 的对象,它包含两个 ArrayList - oldBooks 和 newBooks - 两者都包含 Book 对象.

I have an object called FormObject that contains two ArrayLists - oldBooks and newBooks - both of which contain Book objects.

oldBooks 允许包含重复的 Book 对象newBooks 不允许在其内部包含重复的 Book 对象,并且不能在 oldBooks 列表中包含任何重复的 Book 对象.

oldBooks is allowed to contain duplicate Book objects newBooks is not allowed to contain duplicate Book objects within itself and cannot include any duplicates of Book objects in the oldBooks list.

重复 Book 的定义很复杂,我无法覆盖 equals 方法,因为该定义在 Book 对象的所有用途中并不通用.

The definition of a duplicate Book is complex and I can't override the equals method as the definition is not universal across all uses of the Book object.

我计划在 FormObject 类上有一个名为 removeDuplicateNewBooks 的方法,它将执行上述功能.

I plan to have a method on the FormObject class called removeDuplicateNewBooks which will perform the above functionality.

您将如何实施?我的第一个想法是使用 HashSets 来消除重复项,但无法覆盖 Book 对象上的 equals 意味着它不起作用.

How would you go about implementing this? My first thought was to use HashSets to eliminate the duplicates but not being able to override equals on the Book object means it won't work.

推荐答案

您可以使用 TreeSet 与自定义 Comparator:

  • 使用 Comparator 构建 TreeSet,实现您想要的自定义逻辑
  • 使用 set.addAll(bookList)
  • construct the TreeSet with a Comparator implementing the custom logic you want
  • use set.addAll(bookList)

现在 Set 只包含独特的书籍.

Now the Set contains only unique books.

这篇关于比较两个列表并从中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)