Scala Collections - ListSet


Scala Set is a collection of pairwise different elements of the same type. In other words, a Set is a collection that contains no duplicate elements. ListSet implements immutable sets and uses list 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 list-set of Strings which has three members. Values can be added by using commands like the following −

Command

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

Processing ListSet

Below is an example program of showing how to create, initialize 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