1

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
    Did you try something so far ? Commented 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+sort Commented Dec 3, 2016 at 12:04

3 Answers 3

16

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

you can use List(1 to 400000).sorted

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.