Reputation: 4877
Is there a recommended way to check whether two scala collection Set
s have a non-empty intersection? There is of course the obvious
set1.intersect(set2).isEmpty
But that actually constructs the intersection set first, unless I am mistaken. Is there a better/faster way?
Upvotes: 3
Views: 2366
Reputation: 2196
I'd recommend this:
set1.exists(set2.contains)
Not nearly as readable as "set1.intersectionNonEmpty(set2)", but you could read it as "In set1, there exists some element that set2 contains".
Upvotes: 3
Reputation: 494
The idiomatic way is to use .intersect() or .diff() but both ways build new collection internally.
Fastest ways are:
Upvotes: 3