I'm looking for something to check if two collecti...
# getting-started
h
I'm looking for something to check if two collections overlap, but couldn't find anything in the Stdlib. So I came up with
Copy code
fun <T> Collection<T>.overlaps(other: Collection<T>): Boolean = any { other.contains(it) }
Is there a better way to do this?
h
When I looked a while ago I couldn't find anything in stdlib. I have used this
Copy code
infix 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.
n
Chiming in, if these collections are sufficiently large, it might be worth transforming the smaller collection into a
HashSet
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.