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.
contains() method check if a collection contains a given object, using the . equals() method to perform the comparison. Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ?
contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element. Otherwise, it returns false .
There are two types of collections in Scala – mutable and immutable.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With