用Java比较两个集合的最快方法是什么? [英] What is the fastest way to compare two sets in Java?

查看:717
本文介绍了用Java比较两个集合的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

谢谢

Shekhar

推荐答案

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).

这篇关于用Java比较两个集合的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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