Scala program to check a Map collection is empty

Here, we are going to learn how to check a Map collection is empty in Scala programming language?
Submitted by Nidhi, on June 10, 2021 [Last updated : March 11, 2023]

Scala - Check an Empty Map

Here, we will create empty and non-empty Map collections. Then we will check Map collection is empty or not using the isEmpty method and print appropriate messages on the console screen.

Scala code to check a Map collection is empty

The source code to check a Map collection is empty is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to check a 
// Map collection is empty

object Sample {
  // Main method
  def main(args: Array[String]) {
    var employees: Map[String, String] = Map.empty[String, String];
    var students = Map((101, "Amit"), (102, "Arun"), (103, "Anit"));

    if (employees.isEmpty)
      println("Employees-> Empty Map");
    else
      println("Employees-> Non-empty Map");

    if (students.isEmpty)
      println("Students -> Empty Map");
    else
      println("Students -> Non-empty Map");
  }
}

Output

Employees-> Empty Map
Students -> Non-empty Map

Explanation

Here, we used an object-oriented approach to create the program. And, 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 two maps students, employees. The students map contains the student id and student name. The employee is an empty Map collection. Then we checked Map is empty or not using the isEmpty method and printed the appropriate messages on the console screen.

Scala Map Programs »





Comments and Discussions!

Load comments ↻





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