How to sort a list in scala

I am a newbie in scala and I need to sort a very large list with 40000 integers. The operation is performed many times. So performance is very important. What is the best method for sorting?

2

3 Answers

You can sort the list with List.sortWith() by providing a relevant function literal. For example, the following code prints all elements of sorted list which contains all elements of the initial list in alphabetical order of the first character lowercased:

val initial = List("doodle", "Cons", "bible", "Army")
val sorted = initial.sortWith((s: String, t: String) => s.charAt(0).toLower < t.charAt(0).toLower)
println(sorted)

Much shorter version will be the following with Scala's type inference:

val initial = List("doodle", "Cons", "bible", "Army")
val sorted = initial.sortWith((s, t) => s.charAt(0).toLower < t.charAt(0).toLower)
println(sorted)

For integers there is List.sorted, just use this:

val list = List(4, 3, 2, 1)
val sortedList = list.sorted
println(sortedList)

just check the docs

List has several methods for sorting. myList.sorted works for types with already defined order (like Int or String and others). myList.sortWith and myList.sortBy receive a function that helps defining the order

Also, first link on google for scala List sort:

you can use List(1 to 400000).sorted

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like