How to check if collection contains any element from other collection in Scala?

toucheqt picture toucheqt · Jun 17, 2016 · Viewed 10.7k times · Source

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.

Answer

Peter Neyens picture Peter Neyens · Jun 17, 2016

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