hho
08/07/2025, 9:55 AMfun <T> Collection<T>.overlaps(other: Collection<T>): Boolean = any { other.contains(it) }
Is there a better way to do this?Huib Donkers
08/07/2025, 10:37 AMinfix fun <E> Collection<E>.intersects(other: Collection<E>) = !java.util.Collections.disjoint(this, other)
This should make a couple of optimized choices compared to just any { other.contains(it) }
when one of the collection is a set, or when one of them is smaller than the other.
The stdlib does have intersect
, but (collectionA intersect collectionB).isNotEmpty()
is not as efficient or readable.Nicolai C.
08/08/2025, 10:26 AMHashSet
to improve performance, as the contains call for a HashSet
is O(1).
The reason I'm saying the smaller collection is that I'd assume that creating a HashSet
from the larger collection is more expensive than doing lookups in the smaller collection for each element in the larger collection.