Home »
Scala
How to convert a Set to a SortedSet in Scala?
By IncludeHelp Last updated : November 14, 2024
Scala Set
In Scala, a Set is a collection of elements of the same type. All elements of the set are unique i.e. no elements are allowed. Sets can be mutable as well as immutable.
Scala SortedSet
It is a set in which all elements of the set are arranged in sorted order.
Example:
{1, 4 , 7, 9, 10, 12, 24, 65, 90}
Convert a Set to a SortedSet
To convert a set into sortedSet, there are multiple methods,
object MyClass {
def main(args: Array[String]): Unit = {
val set = Set(2, 56, 577,12 , 46,9, 90, 19);
println("The set is : "+ set)
val sortedSet = collection.immutable.SortedSet[Int]() ++ set
println("The sorted set is : "+ sortedSet)
var sortedSet2 = collection.immutable.TreeSet[Int]() ++ set
println("The sorted set is : "+ sortedSet2)
var sortedSet3 = collection.mutable.SortedSet(set.toList: _*)
println("The sorted set is : "+ sortedSet3)
}
}
Output
The set is : HashSet(56, 46, 9, 2, 577, 12, 19, 90)
The sorted set is : TreeSet(2, 9, 12, 19, 46, 56, 90, 577)
The sorted set is : TreeSet(2, 9, 12, 19, 46, 56, 90, 577)
The sorted set is : TreeSet(2, 9, 12, 19, 46, 56, 90, 577)
The first two methods that are used here ("SortedSet" and "TreeSet") are used to sort immutable sets in Scala and take set as input and return the sorted set.
The last method is SortedSet working over mutable sets too and take the list conversion of the set to sort.