Home » Scala language

How to sort Scala Collections?

Scala | Sorting collections: Here, we are going to learn about the different methods to sort Scala collections.
Submitted by Shivang Yadav, on April 17, 2020

The collection includes all those data structures that are used to store multiple elements or collections of elements like Array, List, Set, Vector, etc.

While working with collection sorting them can be beneficial to the programmers are comparison operators are quite effective.

To sort collections there are some methods provided to you and here we will learn how to use them,

1) Using sorted method

The sorted method is used to sort collections in Scala.

Syntax:

    val sortedColl = Coll.sorted 

Program:

object MyObject {
    def main(args: Array[String]) {
        val seq = Seq(92.23 , 43.12 , 31.2, 7.87)
    
        println("Unsorted Sequence: " + seq)   
    
        val sortedSeq = seq.sorted
        println("Sorted Sequence: " + sortedSeq)   
    
        val lang = Vector("Scala" ,"C" , "HTML" , "Python", "Java")
        println("Unsorted String Vector: " + lang)
    
        val sortedLang = lang.sorted
        println("Sorted String Vector: " + sortedLang)
}
}

Output

Unsorted Sequence: List(92.23, 43.12, 31.2, 7.87)
Sorted Sequence: List(7.87, 31.2, 43.12, 92.23)
Unsorted String Vector: Vector(Scala, C, HTML, Python, Java)
Sorted String Vector: Vector(C, HTML, Java, Python, Scala)

2) Using sortWith() Method

The sortWith() method sorts elements of the collection the way you want.

    sortWith(condition)

Program:

object MyObject {
    def main(args: Array[String]) {
        val seq = Seq(92.23 , 43.12 , 31.2, 7.87)

        println("Unsorted Sequence: " + seq)   

        val sortedSeq = seq.sortWith(_>_)
        println("Sorted Sequence: " + sortedSeq)   

        val lang = Vector("Scala" ,"C" , "HTML" , "Python", "Java")
        println("Unsorted String Vector: " + lang)

        val sortedLang = lang.sortWith(_.length<_.length)
        println("Sorted String Vector: " + sortedLang)
    }
}

Output

Unsorted Sequence: List(92.23, 43.12, 31.2, 7.87)
Sorted Sequence: List(92.23, 43.12, 31.2, 7.87)
Unsorted String Vector: Vector(Scala, C, HTML, Python, Java)
Sorted String Vector: Vector(C, HTML, Java, Scala, Python)





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.