Scala program to demonstrate the Set collection

Here, we are going to demonstrate the Set collection in Scala programming language.
Submitted by Nidhi, on June 25, 2021 [Last updated : March 11, 2023]

Scala - Create a Set collection

Here, we will demonstrate Set collection. Here we will create an empty set, set of strings, and set of numbers. After that, we will print created sets on the console screen.

Scala code to create a Set collection

The source code to demonstrate Set collection is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the
// Set collection

import scala.collection.immutable._

object Sample {
  // Main method
  def main(args: Array[String]) {
    // An empty set
    val emptySet = Set()

    // Set of cities.
    val cities = Set("DELHI", "MUMBAI", "AGRA", "GWALIOR")

    // Set of cities.
    val luckyNumber = Set(111, 786, 555);

    println("Empty Set: \n\t" + emptySet);
    println("Set of cities: \n\t" + cities);
    println("Lucky number: \n\t" + luckyNumber);
  }
}

Output

Empty Set: 
	Set()
Set of cities: 
	Set(DELHI, MUMBAI, AGRA, GWALIOR)
Lucky number: 
	Set(111, 786, 555)

Explanation

Here, we used an object-oriented approach to create the program. And, we imported Collection classes using below statement,

import scala.collection.immutable._

Here, we also created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created an empty set, set of cities, and set of lucky numbers. After that, we printed elements of created sets on the console screen.

Scala Set Programs »





Comments and Discussions!

Load comments ↻





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