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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.