chaotic3quilibrium
chaotic3quilibrium

Reputation: 5924

With Scala's Set, is there a method analog to the containsAll method in Java's Set?

While working through converting some Java code over to Scala, I discovered while there is a contains method for Scala's Set, there isn't a containsAll method. Am I just missing the correct method name?

Here's a bit of code I worked up to fill in the gap so I could quickly get back to working. Is it sufficient, or am I missing some subtlety?

  def containsAll[A](set: Set[A], subset: Set[A]): Boolean =
    if (set.size >= subset.size)
      subset.forall(a => set.contains(a))
    else
      false

Upvotes: 26

Views: 14036

Answers (4)

Michael Zajac
Michael Zajac

Reputation: 55569

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

Upvotes: 40

vasigorc
vasigorc

Reputation: 962

Previous answers are all good, I'm just throwing-in another option. This one would also work with Lists which don't have subsetOf method:

Set(1,2,3) forall(Set(3, 2, 1) contains)

Upvotes: 2

Ben Reich
Ben Reich

Reputation: 16324

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)

Upvotes: 7

elm
elm

Reputation: 20415

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.

Upvotes: 8

Related Questions