如何最好比较两个集合在Java和行动他们? [英] How Best to Compare Two Collections in Java and Act on Them?

查看:124
本文介绍了如何最好比较两个集合在Java和行动他们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同对象的集合, Collection< Foo> oldSet Collection< Foo> newSet 。所需的逻辑如下:




  • 如果 foo 在(*) oldSet 但不是 newSet ,调用 doRemove(foo) li>
  • else if foo 不在 oldSet newSet ,调用 doAdd(foo)

  • else if foo 在两个集合中但是已修改,调用 doUpdate(oldFoo,newFoo)

  • !foo.activated&&& foo.startDate> = now ,调用 doStart(foo)

  • else if foo.activated&&& foo.endDate< = now ,调用 doEnd(foo)


b $ b

(*)in表示唯一标识符匹配,不一定是内容。



当前 removeSet addSet updateSet startSet endSet ,然后循环执行每个项目。



代码是相当混乱(部分是因为我已经省略了一些意大利面条逻辑),我试图重构它。更多背景信息:




  • 据我所知, oldSet code> newSet 实际上支持 ArrayList

  • 每个集合包含少于100个项目,

$ b $ 这个程式码经常被呼叫(以百万/天为单位) b

我的问题:




  • 如果我转换 oldSet newSet HashMap< Foo> (这里不关心顺序)使代码更容易阅读和更容易比较?多少时间&内存性能是转换损失吗?

  • 迭代两个集合并执行适当的操作更有效率和简洁?

$ b $ Apache的commons.collections库有一个CollectionUtils类,为集合操作/检查提供了易于使用的方法,如交集,差异和联合。



org.apache.commons.collections.CollectionUtils API文件此处


I have two collections of the same object, Collection<Foo> oldSet and Collection<Foo> newSet. The required logic is as follow:

  • if foo is in(*) oldSet but not newSet, call doRemove(foo)
  • else if foo is not in oldSet but in newSet, call doAdd(foo)
  • else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
  • else if !foo.activated && foo.startDate >= now, call doStart(foo)
  • else if foo.activated && foo.endDate <= now, call doEnd(foo)

(*) "in" means the unique identifier matches, not necessarily the content.

The current (legacy) code does many comparisons to figure out removeSet, addSet, updateSet, startSet and endSet, and then loop to act on each item.

The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info:

  • As far as I know, the oldSet and newSet are actually backed by ArrayList
  • Each set contains less than 100 items, most likely max out at 20
  • This code is called frequently (measured in millions/day), although the sets seldom differ

My questions:

  • If I convert oldSet and newSet into HashMap<Foo> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion?
  • Would iterating the two sets and perform the appropriate operation be more efficient and concise?

解决方案

Apache's commons.collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union.

The org.apache.commons.collections.CollectionUtils API docs are here.

这篇关于如何最好比较两个集合在Java和行动他们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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