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
The containsAll() method of Java AbstractCollection class The containsAll() method checks for all the elements in the specified collection. It returns TRUE if this collection has all the elements. The methods check for each element one by one to see if it's contained in this collection.
The contains() method is utilized to check if an element is present in the set of not. Return Type: It returns true if the element is present in the set else it returns false.
There are two kinds of Sets, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Set.
++= can mean two different things in Scala: 1: Invoke the ++= method. In your example with flatMap , the ++= method of Builder takes another collection and adds its elements into the builder. Many of the other mutable collections in the Scala collections library define a similiar ++= method.
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.
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