×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to create a mutable set in Scala?

By IncludeHelp Last updated : November 14, 2024

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)

Mutable Set

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 to Create a Mutable Set

object MyClass {
    def main(args: Array[String]): Unit = {
        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.