在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();
}
发布于 2019-04-03 18:59:46
通过streams/reduce进行交集计数(它假设您在调用它之前确定了哪个集合更大):
public int countIntersect(Set<Integer> largerSet, Set<Integer> smallerSet){
return smallerSet.stream().reduce(0, (a,b) -> largerSet.contains(b)?a+1:a);
}
然而,我在其他地方读到,没有java代码可以比Set操作的set方法更快,因为它们是作为本机代码而不是java代码实现的。因此,我建议尝试使用BitSet以更快地获得结果。
https://stackoverflow.com/questions/7574311
复制相似问题