scala 如何在Scala中对列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40945873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 08:53:33  来源:igfitidea点击:

How to sort a list in scala

scala

提问by user7244518

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?

我是 Scala 的新手,我需要对一个包含 40000 个整数的非常大的列表进行排序。该操作执行多次。所以性能非常重要。最好的排序方法是什么?

回答by CavaJ

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

您可以List.sortWith()通过提供相关的函数文字来对列表进行排序。例如,以下代码按第一个小写字符的字母顺序打印sorted包含列表所有元素的列表的所有元素initial

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:

更短的版本将是以下带有 Scala类型推断的

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:

对于整数有List.sorted,只需使用这个:

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

回答by pedrorijo91

just check the B)(implicitord:scala.math.Ordering[B]):Repr" rel="nofollow noreferrer">docs

只需检查B)(implicitord:scala.math.Ordering[B]):Repr" rel="nofollow noreferrer">文档

List has several methods for sorting. myList.sortedworks for types with already defined order (like Intor Stringand others). myList.sortWithand myList.sortByreceive a function that helps defining the order

List 有几种排序方法。myList.sorted适用于已定义顺序的类型(如IntString等)。myList.sortWithmyList.sortBy接收一个有助于定义订单的函数

Also, first link on google for scala List sort: http://alvinalexander.com/scala/how-sort-scala-sequences-seq-list-array-buffer-vector-ordering-ordered

此外,谷歌上的第一个链接scala List sorthttp: //alvinalexander.com/scala/how-sort-scala-sequences-seq-list-array-buffer-vector-ordering-ordered

回答by HuntsMan

you can use List(1 to 400000).sorted

你可以使用 List(1 to 400000).sorted