如何最好地比较 Java 中的两个集合并对其采取行动? [英] How Best to Compare Two Collections in Java and Act on Them?

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

问题描述

我有同一个对象的两个集合,CollectionoldSetCollection新集.所需逻辑如下:

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 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" 表示唯一标识符匹配,不一定是内容.

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

当前(遗留)代码做了很多比较以找出removeSetaddSetupdateSetstartSetendSet,然后循环对每个项目进行操作.

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:

  • 据我所知,oldSetnewSet 实际上是由 ArrayList
  • 支持的
  • 每组包含少于 100 个项目,最有可能最多 20 个
  • 此代码被频繁调用(以百万/天为单位),尽管集合很少不同

我的问题:

  • 如果我将 oldSetnewSet 转换为 HashMap(这里不关心顺序),以 ID 作为键,它会使代码更易于阅读和比较吗?多少时间&内存性能是转换时的损失?
  • 迭代这两个集合并执行适当的操作会更高效和简洁吗?
  • 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 的 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屋!

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