我需要为单元测试执行此操作。正在测试的方法返回一个 ImmutbaleMap,我需要能够将它与我已有的方法进行比较。一种方法是获取两个键集(keySets()),运行它们并比较从两个映射返回的值以获取这些键。然而,对我来说这似乎有点低效。有更好/首选的方法吗?
最佳答案
如果键和值都正确实现了 equals()
,则可以简单地使用 Map.equals()
:
Compares the specified object with this map for equality. Returns
true
if the given object is also a map and the two maps represent the same mappings. More formally, two mapsm1
andm2
represent the same mappings ifm1.entrySet().equals(m2.entrySet())
. This ensures that theequals
method works properly across different implementations of theMap
interface.
如果他们不这样做,我怀疑您是否会找到一款开箱即用的单行代码。我希望您必须自己进行比较。这并不难做到:
- 如果 symmetric difference两个键集之间不为空,就完成了。
- 否则,迭代一个映射,在另一个映射中查找相同的键并比较值(使用任何合适的比较方法)。
这可以轻松封装到辅助函数中,也许可以通过值比较器进行参数化。
关于java - 如何确认两个 ImmutableMap 具有完全相同的(键,值)对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626257/