Scala program to check the given element exists in a Set collection or not

Here, we are going to learn how to check the given element exists in a Set collection or not in Scala programming language?
Submitted by Nidhi, on June 26, 2021 [Last updated : March 11, 2023]

Check a Number Present in Scala Set

Here, we will create a set of cities using the Set collection class. Then we will read the city from the user and check entered city is exists in the set or not using contains() method.

Scala code to check the given element exists in a Set collection or not

The source code to check the given element exists in a Set collection or not is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to check the given element 
// is exist in a Set collection or not

import scala.collection.immutable._

object Sample {
  // Main method
  def main(args: Array[String]) {
    //Set of cities.
    val cities = Set("DELHI", "MUMBAI", "AGRA", "GWALIOR");
    var city: String = "";

    printf("Enter city: ");
    city = scala.io.StdIn.readLine();

    if (cities.contains(city))
      println(city + " exists in cities Set.");
    else
      println(city + " does not exist in cities Set.");
  }
}

Output

Enter city: GWALIOR
GWALIOR exists in cities Set

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 a set of cities using the Set collection class. Then we read a city from the user and checked entered city exists in the cities collection using contains() method. Then printed the appropriate message on the console screen.

Scala Set Programs »






Comments and Discussions!

Load comments ↻






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