如何最好比较两个集合在Java和行动他们? [英] How Best to Compare Two Collections in Java and Act on Them?
问题描述
我有两个相同对象的集合, 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个项目,
我的问题:
- 如果我转换
oldSet
和newSet
到HashMap< Foo>
(这里不关心顺序)使代码更容易阅读和更容易比较?多少时间&内存性能是转换损失吗? - 迭代两个集合并执行适当的操作更有效率和简洁?
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 notnewSet
, calldoRemove(foo)
- else if
foo
is not inoldSet
but innewSet
, calldoAdd(foo)
- else if
foo
is in both collections but modified, calldoUpdate(oldFoo, newFoo)
- else if
!foo.activated && foo.startDate >= now
, calldoStart(foo)
- else if
foo.activated && foo.endDate <= now
, calldoEnd(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
andnewSet
are actually backed byArrayList
- 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
andnewSet
intoHashMap<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屋!