×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to sort Scala Collections?

By IncludeHelp Last updated : November 14, 2024

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 

Example

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

Syntax

sortWith(condition)

Example

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