mitchus
mitchus

Reputation: 4877

Checking whether scala set intersection is empty

Is there a recommended way to check whether two scala collection Sets 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

Answers (2)

mike
mike

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

Artur Rashitov
Artur Rashitov

Reputation: 494

The idiomatic way is to use .intersect() or .diff() but both ways build new collection internally.

Fastest ways are:

  • Manually iterate over first set until match in the second
  • Use probabilistic Bloom Filter that take some time to construct it but can compare two sets (even very huge) very fast (occasionally may give false positives)

Upvotes: 3

Related Questions