Set is a data structure which allows us to store elements which are unique. The ordering of elements does not guarantee by the Set, than a TreeSet will make elements in a given order. In Scala, TreeSet have two versions:
scala.collection.immutable.TreeSet and
scala.collection.mutable.TreeSet.
Syntax:
var TreesetName = TreeSet(element1, element2, element3, ....)
Operations perform with TreeSet
Initialize a TreeSet :
Below is the example to create or initialize TreeSet.
Example:
Output:
Initialize a TreeSet
Elements are = TreeSet(Author, Geeks, GeeksForGeeks)
Check specific elements in TreeSet :
Example:
Output:
Initialize a TreeSet
Elements are = TreeSet(Author, Geeks, GeeksForGeeks)
Element Geeks = true
Element Student = false
Adding an element in TreeSet :
We can add an element in TreeSet by using
+ sign. below is the example of adding an element in TreeSet.
Example:
Output:
Initialize a TreeSet
Elements are = TreeSet(Author, Geeks, GeeksForGeeks)
Adding elements to TreeSet = TreeSet(Author, Geeks, GeeksClasses, GeeksForGeeks)
Adding two TreeSets in TreeSets :
We can add two TreeSets by using ++ sign. below is the example of adding two TreeSets.
Example:
Output:
Initialize a TreeSet
Elements are = TreeSet(Author, Geeks, GeeksForGeeks)
Add more than one TreeSets = TreeSet(Author, Geeks, GeeksForGeeks, Java, Scala)
Remove element in TreeSet :
We can remove an element in TreeSet by using – sign. below is the example of removing an element in TreeSet.
Example:
Output:
Initialize a TreeSet
Elements are = TreeSet(Author, Geeks, GeeksForGeeks)
remove element from treeset = TreeSet(Author, GeeksForGeeks)
Find the intersection between two TreeSets :
We can find intersection between two TreeSets by using & sign. below is the example of finding intersection between two TreeSets.
Example:
Output:
Initialize two TreeSets
Elements of treeset1 are = TreeSet(Author, Geeks, GeeksForGeeks)
Elements of treeset2 are = TreeSet(Geeks, Java, Scala)
Intersection of treeSet1 and treeSet2 = TreeSet(Geeks)
Initializing an empty TreeSet :
Below is the example to show empty TreeSet.
Example:
Output:
Empty TreeSet = TreeSet()