With Scala's Set, is there a method analog to the containsAll method in Java's Set?
There is subsetOf
, which tests whether or not the elements of a Set
are contained within another Set
. (Kind of the reverse in terms of the expression)
val set = Set(1,2,3,4)
val subset = Set(1,2)
scala> subset.subsetOf(set)
res0: Boolean = true
scala> set.subsetOf(subset)
res1: Boolean = false
In Scala, Set
is equipped with set operations such as intersect
, thus for instance
set.intersect(subset) == subset
conveys the semantics of containsAll
, even that subsetOf
as already mentioned proves the most succinct.
It's worth adding that you can make derived helper methods like containsAll
available on Set[T]
if you want, by using an implicit enriched class. You might also consider making a variadic overload:
implicit class RichSet[T](val x: Set[T]) extends AnyVal {
def containsAll(y: Set[T]): Boolean = y.subsetOf(x)
def containsAll(y: T*): Boolean = x.containsAll(y.toSet)
}
So then you can do:
Set(1, 2, 3).containsAll(Set(1, 2))
Or:
Set(1, 2, 3).containsAll(1, 2)