Q:

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

belongs to collection: Scala Set Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to add and remove elements from the ... >>
<< Scala program to merge two sets using the ++ opera...