How to check if collection contains any element from other collection in Scala?
Solution 1
You can use a combination of exists(p: T => Boolean):Boolean
and contains(elem: A1):Boolean
:
val a = List(1,2,3,4,5,6,7)
val b = List(11,22,33,44,55,6)
a.exists(b.contains) // true
Solution 2
Intersect
val a = Seq(1,2,3) ; val b = Seq(2,4,5)
a.intersect(b)
res0: Seq[Int] = List(2)
// to include the test:
a.intersect(b).nonEmpty // credit @Lukasz
Solution 3
Using disjoint()
from the standard Java Collections
utilities can determine if two collections contain any common members. If the collections are not disjoint, then they contain at least one common element.
Internally, Collections.disjoint()
checks if either collection is a Set
and optimizes accordingly.
import collection.JavaConverters._
val a = List(1,2,3,4,5,6,7)
val b = List(11,22,33,44,55,6)
!java.util.Collections.disjoint(a.asJava, b.asJava) // true
Although this is still converting the Scala collection to a Java collection. On the plus side, the extra apache commons library isn't needed.
toucheqt
Updated on June 03, 2022Comments
-
toucheqt almost 2 years
Title says it all, what is the best practice for finding out if collection contains any element of other collection?
In java I would execute it like this
CollectionUtils.containsAny(a, b)
using common apache collection utils, where variables a/b are collections.
How to implement this behavior in scala? Or is there library like CollectionUtils from above?
I dont want to use the common-apache library because i would have to convert scala collection to java collection.
-
Alexander Aleksandrovič Klimov almost 8 yearsNot sure why it got a downvote. It's the obvious answer
-
Łukasz almost 8 yearsIt could look cleaner as
a.intersect(b).nonEmpty
. -
pedrofurla almost 8 yearsThe obvious answer is the other one, @TheArchetypalPaul. Anyways, I didn't downvote, just didn't vote.
-
Alexander Aleksandrovič Klimov almost 8 yearsSince the question is actually "do the two arrays have any elements in common" I still feel intersect of the obvious answer. It certainly didn't need a down vote. Imo obviously
-
WestCoastProjects almost 8 years@Łukasz Thx for the nonEmpty (vs !isEmpty)
-
conny almost 6 yearsThat makes sense... but I'd argue it doesn't make for much readability 😳
-
conny almost 6 yearsIsn't it wasteful to have to create an intersection just to check whether it is nonEmpty? I think that is why people vote for the other solution.