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?
-
3Did you try something so far ?Yanga– Yanga2016-12-03 09:09:00 +00:00Commented Dec 3, 2016 at 9:09
-
I suggest you do some research and come back with more specific questions. An starting point: stackoverflow.com/search?q=%5Bscala%5D+sortmaasg– maasg2016-12-03 12:04:49 +00:00Commented Dec 3, 2016 at 12:04
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)
Comments
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: http://alvinalexander.com/scala/how-sort-scala-sequences-seq-list-array-buffer-vector-ordering-ordered