在Java中,找到两个非稀疏集合的交集大小的最有效方法是什么?这是一个我将在大型集合上调用非常多次的操作,因此优化是重要的。我不能修改原始集。
我看过Apache Commons的CollectionUtils.intersection,它看起来相当慢。我目前的方法是取两个集合中较小的一个,克隆它,然后在两个集合中较大的一个上调用.retainAll。
public static int getIntersection(Set<Long> set1, Set<Long> set2) {
boolean set1IsLarger = set1.size() > set2.size();
Set<Long> cloneSet = new HashSet<Long>(set1IsLarger ? set2 : set1);
cloneSet.retainAll(set1IsLarger ? set1 : set2);
return cloneSet.size();
}发布于 2011-09-28 03:02:15
只需使用Google Guava的Sets#intersection(Set, Set)方法即可。
发布于 2011-09-28 03:02:10
可以轻松地将集合的成员映射到相对较小的整数范围内吗?如果是这样,请考虑使用BitSets。交集就是按位的,一次- 32个潜在成员。
发布于 2013-01-30 02:30:26
通过使用Set方法retainAll(),可以避免所有手动操作。
来自文档:
s1.retainAll( s2 ) -将s1转换为s1和s2的交集。(两个集合的交集是仅包含两个集合的公共元素的集合。)
https://stackoverflow.com/questions/7574311
复制相似问题