Scala Collections - TreeSet



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. TreeSet implements immutable sets and keeps elements in sorted order.

Declaring TreeSet Variables

The following is the syntax for declaring an TreeSet variable.

Syntax

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

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

Command

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

Processing TreeSet

Below is an example program of showing how to create, initialize and process TreeSet −

Example

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      var mySet: TreeSet[String] = TreeSet("Zara","Nuha","Ayan");
      // Add an element
      var mySet1: TreeSet[String] = mySet + "Naira";
      // Remove an element
      var mySet2: TreeSet[String] = mySet - "Nuha";
      // Create empty set
      var mySet3: TreeSet[String] = TreeSet.empty[String];
      println(mySet);
      println(mySet1);
      println(mySet2);
      println(mySet3);	  
   }
}

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

TreeSet(Ayan, Nuha, Zara)
TreeSet(Ayan, Naira, Nuha, Zara)
TreeSet(Ayan, Zara)
TreeSet()

Checking Membership

You can check if a value is present in a TreeSet using the contains method. This method returns true if the value is present and false otherwise.

Example

Try the following example for checking membership whether these exist or not -

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      var mySet: TreeSet[String] = TreeSet("Zara", "Nuha", "Ayan")
      // Check if the TreeSet contains "Nuha"
      println(mySet.contains("Nuha"))
      // Check if the TreeSet contains "Naira"
      println(mySet.contains("Naira"))
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

true
false

Common Set Operations

You can perform various common set operations such as union, intersection, and difference on TreeSet. These operations are useful for comparing and combining sets.

  • Union: For all unique elements from both sets.
  • Intersection: For common unique elements from both sets.
  • Difference: For elements from the first set that are not in the second set.

Example

Try the following example for these set operations -

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      val set1: TreeSet[String] = TreeSet("Zara", "Nuha", "Ayan")
      val set2: TreeSet[String] = TreeSet("Ayan", "Naira", "Maira")

      // Perform union operation
      val unionSet = set1 union set2
      println("Union: " + unionSet)

      // Perform intersection operation
      val intersectionSet = set1 intersect set2
      println("Intersection: " + intersectionSet)

      // Perform difference operation
      val differenceSet = set1 diff set2
      println("Difference: " + differenceSet)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Union: TreeSet(Ayan, Maira, Naira, Nuha, Zara)
Intersection: TreeSet(Ayan)
Difference: TreeSet(Nuha, Zara)

Finding Maximum and Minimum Elements

You can find the maximum and minimum elements in a TreeSet using the max and min methods, respectively.

Example

Try the following example for finding max and min elements in TreeSet -

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      val numbers: TreeSet[Int] = TreeSet(5, 2, 8, 1, 4)
      // Find the maximum element
      println("Max element: " + numbers.max)
      // Find the minimum element
      println("Min element: " + numbers.min)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Max element: 8
Min element: 1

Subset and Superset

You can check if one TreeSet is a subset of another using the subsetOf method. Similarly, you can check if a set is a superset of another using the supersetOf method.

Example

Try the following example for checking subset and superset in TreeSet -

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      val set1: TreeSet[String] = TreeSet("Zara", "Nuha")
      val set2: TreeSet[String] = TreeSet("Zara", "Nuha", "Ayan")
      // Check if set1 is a subset of set2
      val isSubset = set1.subsetOf(set2)
      println("Is set1 a subset of set2? " + isSubset)
      // Check if set2 is a superset of set1
      val isSuperset = set2.subsetOf(set1)
      println("Is set2 a superset of set1? " + isSuperset)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Is set1 a subset of set2? true
Is set2 a superset of set1? false

Mutable TreeSet

While TreeSet in Scala is immutable by default, Scala also provides mutable versions of sets. Mutable sets allow in-place modification of elements.

Declaring Mutable TreeSet

To use a mutable TreeSet, you need to import scala.collection.mutable.TreeSet.

Syntax

import scala.collection.mutable.TreeSet
var z: TreeSet[String] = TreeSet("Zara", "Nuha", "Ayan")

Example

import scala.collection.mutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      var mySet: TreeSet[String] = TreeSet("Zara", "Nuha", "Ayan")
      // Add an element to the mutable TreeSet
      mySet += "Naira"
      // Remove an element from the mutable TreeSet
      mySet -= "Nuha"
      // Print the modified TreeSet
      println(mySet)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

TreeSet(Ayan, Naira, Zara)

Transforming Elements

You can transform the elements of a TreeSet using the map method. This method applies a function to each element of the set and returns a new set with the transformed elements.

Try the following example for doubling each element of TreeSet -

Example

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      val numbers: TreeSet[Int] = TreeSet(1, 2, 3, 4, 5)
      // Transform the elements by doubling them
      val doubled = numbers.map(_ * 2)
      println(doubled)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

TreeSet(2, 4, 6, 8, 10)

Filtering Elements

You can filter elements of a TreeSet using the filter method. This method returns a new set containing only the elements that satisfy a given predicate.

Try the following example for filtering even numbers in TreeSet -

Example

import scala.collection.immutable.TreeSet

object Demo {
   def main(args: Array[String]) = {
      val numbers: TreeSet[Int] = TreeSet(1, 2, 3, 4, 5)
      // Filter elements that are even
      val evens = numbers.filter(_ % 2 == 0)
      println(evens)
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

TreeSet(2, 4)

TreeSet Summary

  • TreeSet is a collection of unique elements in sorted order.
  • TreeSet is immutable by default, but mutable versions are also available.
  • You can add, remove, and check for elements in a TreeSet.
  • Common set operations such as union, intersection, and difference can be performed on TreeSet.
  • You can find the maximum and minimum elements in a set.
  • You can check for subset and superset relationships between sets.
  • You can transform and filter elements in a TreeSet.
Advertisements