比较两个列表并从一个列表中删除重复项 [英] Comparing two lists and removing duplicates from one

查看:97
本文介绍了比较两个列表并从一个列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为FormObject的对象,它包含两个ArrayLists - 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对象意味着它不工作。

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 自定义比较器< Book>


  • 使用比较器构建 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆