Home » Scala language

How to create a mutable set in Scala?

Creating a mutable set: In this tutorial on Scala sets, we will learn how to create a mutable set in Scala with example code?
Submitted by Shivang Yadav, on December 03, 2019

Scala Set

In Scala, a Set is a collection of elements of the same type. All elements of the set are unique i.e. no elements are allowed. Sets can be mutable as well as immutable.

Example:

    Set(1, 4, 5, 7, 12, 87, 213)

The mutable set is a set that contains elements that can be changed after the initialization of the set.

A mutable variable in the Scala is declared using the val keyword. And mutable Sets in scala are imported from,

    scala.collection.mutable.Set

Example:

object MyClass {
    def main(args: Array[String]) {
        val set = scala.collection.mutable.Set(2, 56, 577,12 , 46, 19);
        println("The set is : "+set)
        set += 34;
        set += 99;
        println("After adding two elements, the set is "+ set)
    }
}

Output

The set is : HashSet(577, 2, 19, 56, 12, 46)
After adding two elements, the set is HashSet(577, 2, 34, 19, 99, 56, 12, 46)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.