如何最好地比较 Java 中的两个集合并对其采取行动? [英] How Best to Compare Two Collections in Java and Act on Them?
问题描述
我有同一个对象的两个集合,Collection
和 Collection
.所需逻辑如下:
I have two collections of the same object, Collection<Foo> oldSet
and Collection<Foo> newSet
. The required logic is as follow:
- 如果
foo
在 (*)oldSet
但不是newSet
,则调用doRemove(foo)
莉> - else 如果
foo
不在oldSet
中而是在newSet
中,则调用doAdd(foo)
- else 如果
foo
在两个集合中但被修改,则调用doUpdate(oldFoo, newFoo)
- else if
!foo.activated &&foo.startDate >= now
,调用doStart(foo)
- else if
foo.activated &&foo.endDate <= now
,调用doEnd(foo)
- 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" 表示唯一标识符匹配,不一定是内容.
(*) "in" means the unique identifier matches, not necessarily the content.
当前(遗留)代码做了很多比较以找出removeSet
、addSet
、updateSet
、startSet
和 endSet
,然后循环对每个项目进行操作.
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:
- 据我所知,
oldSet
和newSet
实际上是由ArrayList
支持的 - 每组包含少于 100 个项目,最有可能最多 20 个
- 此代码被频繁调用(以百万/天为单位),尽管集合很少不同
我的问题:
- 如果我将
oldSet
和newSet
转换为HashMap
(这里不关心顺序),以 ID 作为键,它会使代码更易于阅读和比较吗?多少时间&内存性能是转换时的损失? - 迭代这两个集合并执行适当的操作会更高效和简洁吗?
- 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 的 commons.collections 库有一个 CollectionUtils 类,该类提供了易于使用的集合操作/检查方法,例如交集、差集和并集.
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.
org.apache.commons.collections.CollectionUtils API 文档是 此处.
The org.apache.commons.collections.CollectionUtils API docs are here.
这篇关于如何最好地比较 Java 中的两个集合并对其采取行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!