在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();
}
https://stackoverflow.com/questions/7574311
复制相似问题