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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.