Set
Immutable Set
  • By default, Scala uses the immutable Set
  • object Demo
    {
      def main(args : Array[String])
      {
        var a = Set(1, 1, 2, 3, 4); // 1, 2, 3, 4
        var b = Set(4, 6, 7, 8, 8);
        println(a)
    
        println(a.head) // head
        println(a.tail) // tail
    
        println(a ++ b) // 5 1 6 2 7 3 8 4
    
        println(a+10) // add an element to set
        println(a-1) // remove an element from set
    
        println(a.apply(1)) // check if set contains a specific element
    
        // intersect
        println(a.&(b))
        println(a.intersect(b))
        // unit
        println(a.union(b))
        // difference
        println(a.&~(b))
    
        // foreach
        a.foreach(println(_))
        // max
        println(a.max)
        // min
        println(a.min)
        // mkString
        println(a.mkString(" "))
      }
    }
    		
    Mutable Set
    import scala.collection.mutable.{Set => mSet}
    object Demo
    {
      def main(args : Array[String])
      {
        var a = mSet(1, 1, 2, 3, 4); // 1, 2, 3, 4
        var b = mSet(4, 6, 7, 8, 8);
    
        // intersect
        println(a.&(b))
        println(a.intersect(b))
        // unit
        println(a.union(b))
        // difference
        println(a.&~(b))
      }
    }
    		
    SortedSet
    import scala.collection.immutable.SortedSet
    object Demo
    {
      def main(args : Array[String])
      {
        var a = SortedSet(1, 1, 4, 3, 2);
        var b = SortedSet(4, 6, 7, 8, 8);
    
        var c = a.toArray
        println(c(1))
    
        // intersect
        println(a.&(b))
        println(a.intersect(b))
        // unit
        println(a.union(b))
        // difference
        println(a.&~(b))
      }
    }
    		
    Reference
  • Immutable Set
  • Mutable Set