在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();
}
Run Code Online (Sandbox Code Playgroud)