在 Java 中比较两组的最快方法是什么?

2022-01-17 00:00:00 performance set java

我正在尝试优化一段比较列表元素的代码.

I am trying to optimize a piece of code which compares elements of list.

例如.

public void compare(Set<Record> firstSet, Set<Record> secondSet){
    for(Record firstRecord : firstSet){
        for(Record secondRecord : secondSet){
            // comparing logic
        }
    }
}

请注意集合中的记录数会很高.

Please take into account that the number of records in sets will be high.

谢谢

谢卡尔

推荐答案

firstSet.equals(secondSet)

这真的取决于你想在比较逻辑中做什么......即如果你在一个集合中找到一个元素而不在另一个集合中会发生什么?你的方法有一个 void 返回类型,所以我假设你会在这个方法中做必要的工作.

It really depends on what you want to do in the comparison logic... ie what happens if you find an element in one set not in the other? Your method has a void return type so I assume you'll do the necessary work in this method.

如果需要,可以进行更细粒度的控制:

More fine-grained control if you need it:

if (!firstSet.containsAll(secondSet)) {
  // do something if needs be
}
if (!secondSet.containsAll(firstSet)) {
  // do something if needs be
}

如果您需要获取一组中的元素而不是另一组中的元素.
set.removeAll(otherSet) 返回一个布尔值,而不是一个集合.要使用 removeAll(),您必须复制该集合然后使用它.

If you need to get the elements that are in one set and not the other.
set.removeAll(otherSet) returns a boolean, not a set. To use removeAll(), you'll have to copy the set then use it.

Set one = new HashSet<>(firstSet);
Set two = new HashSet<>(secondSet);
one.removeAll(secondSet);
two.removeAll(firstSet);

如果 onetwo 的内容都是空的,那么你知道这两个集合是相等的.如果不是,那么你已经得到了使集合不相等的元素.

If the contents of one and two are both empty, then you know that the two sets were equal. If not, then you've got the elements that made the sets unequal.

您提到记录的数量可能很高.如果底层实现是一个HashSet,那么每条记录的获取都是在O(1) 时间内完成的,所以没有比这更好的了.TreeSetO(log n).

You mentioned that the number of records might be high. If the underlying implementation is a HashSet then the fetching of each record is done in O(1) time, so you can't really get much better than that. TreeSet is O(log n).

相关文章