How to check if a collection contains any item from another collection in Scala?

The heading says everything that is best to find out if the collection contains any element of another collection?

In java, I would execute it like this

CollectionUtils.containsAny(a, b) 

using general apache collection utilities, where a / b variables are collections.

How to implement this behavior in scala? Or is there a library like CollectionUtils on top?

I do not want to use the common-apache library because I would have to convert the scala collection to a java collection.

+7
source share
3 answers

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 
+19
source

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 
+11
source

Using disjoint() from the standard Java Collections utilities can determine if the two collections contain any common elements. If collections are not disjoint, then they contain at least one common element.

Internally, Collections.disjoint() checks to see if any collection is 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 it still converts the Scala collection into a Java collection. On the other hand, the additional Apache Commons library is not needed.

0
source

All Articles