Home » Scala language

How to convert a Set to a SortedSet in Scala?

Here, we will learn how to convert a Set to a sortedSet in Scala? Methods to convert a simple set to a SortedSet in Scala programming language.
Submitted by Shivang Yadav, on December 04, 2019

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.

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}

To convert a set into sortedSet, there are multiple methods,

object MyClass {
    def main(args: Array[String]) {
        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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.