English 中文(简体)
Scala Collections - ListSet
  • 时间:2024-10-18

Scala Collections - ListSet


Previous Page Next Page  

Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duppcate elements. ListSet implements immutable sets and uses pst structure. Elements insertion order is preserved while storing the elements.

Declaring ListSet Variables

The following is the syntax for declaring an ListSet variable.

Syntax


var z : ListSet[String] = ListSet("Zara","Nuha","Ayan")

Here, z is declared as an pst-set of Strings which has three members. Values can be added by using commands pke the following −

Command


var myList1: ListSet[String] = myList + "Naira";

Processing ListSet

Below is an example program of showing how to create, initiapze and process ListSet −

Example


import scala.collection.immutable.ListSet
object Demo {
   def main(args: Array[String]) = {
      var myList: ListSet[String] = ListSet("Zara","Nuha","Ayan");
      // Add an element
      var myList1: ListSet[String] = myList + "Naira";
      // Remove an element
      var myList2: ListSet[String] = myList - "Nuha";
      // Create empty set
      var myList3: ListSet[String] = ListSet.empty[String];
      println(myList);
      println(myList1);
      println(myList2);
      println(myList3);	  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command


>scalac Demo.scala
>scala Demo

Output


ListSet(Zara, Nuha, Ayan)
ListSet(Zara, Nuha, Ayan, Naira)
ListSet(Zara, Ayan)
ListSet()
Advertisements