Scala program to check a List collection is empty or not

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

Scala – Check If List Collection is Empty?

Here, we will create two lists of integers using List collection. Then we will check a List collection is empty or not using the isEmpty property and print the appropriate message on the console screen.

The List collection is used to store ordered elements. It extends the LinearSeq trait and is used for the immutable linked list.

Scala code to check a List collection is empty or not

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

// Scala program to check a List collection
// is empty or not

import scala.collection.immutable._

object Sample {
  // Main method
  def main(args: Array[String]) {
    var intList1 = List();
    var intList2 = List(8, 5, 3, 2, 4);

    if (intList1.isEmpty)
      println("intList1 is empty");
    else
      println("intList1 is not empty");

    if (intList2.isEmpty)
      println("intList2 is empty");
    else
      println("intList2 is not empty");
  }
}

Output

intList1 is empty
intList2 is not empty

Explanation

In the above program, we used an object-oriented approach to create the program. Here 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 two lists intList1, intList2 using List collection. Then we used the isEmpty property of the List collection and printed the appropriate message on the console screen.

Scala List Programs »





Comments and Discussions!

Load comments ↻





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