Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 875
chaotic3quilibrium Avatar asked Feb 24 '15 20:02

chaotic3quilibrium


People also ask

How does containsAll work in Java?

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.

How do you check if a set contains an element in Scala?

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.

Is a set immutable in Scala?

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.

What does ++ mean in Scala?

++= 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.


2 Answers

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 
like image 79
Michael Zajac Avatar answered Sep 29 '22 02:09

Michael Zajac


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.

like image 24
elm Avatar answered Sep 29 '22 03:09

elm