scala 如何按两个字段对Scala中的列表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10027543/
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 04:04:51  来源:igfitidea点击:

How to sort a list in Scala by two fields?

scalasortingfunctional-programming

提问by Twistleton

how to sort a list in Scala by two fields, in this example I will sort by lastName and firstName?

如何按两个字段对 Scala 中的列表进行排序,在本例中,我将按 lastName 和 firstName 排序?

case class Row(var firstName: String, var lastName: String, var city: String)

var rows = List(new Row("Oscar", "Wilde", "London"),
                new Row("Otto",  "Swift", "Berlin"),
                new Row("Carl",  "Swift", "Paris"),
                new Row("Hans",  "Swift", "Dublin"),
                new Row("Hugo",  "Swift", "Sligo"))

rows.sortBy(_.lastName)

I try things like this

我尝试这样的事情

rows.sortBy(_.lastName + _.firstName)

but it doesn't work. So I be curious for a good and easy solution.

但它不起作用。所以我很好奇一个好的和简单的解决方案。

回答by senia

rows.sortBy(r => (r.lastName, r.firstName))

回答by user unknown

rows.sortBy (row => row.lastName + row.firstName)

If you want to sort by the merged names, as in your question, or

如果您想按合并名称排序,如您的问题,或

rows.sortBy (row => (row.lastName, row.firstName))

if you first want to sort by lastName, then firstName; relevant for longer names (Wild, Wilder, Wilderman).

如果您首先想按姓氏排序,则按名字排序;与较长的名称相关(Wild、Wilder、Wilderman)。

If you write

如果你写

rows.sortBy(_.lastName + _.firstName)

with 2 underlines, the method expects two parameters:

有 2 个下划线,该方法需要两个参数:

<console>:14: error: wrong number of parameters; expected = 1
       rows.sortBy (_.lastName + _.firstName)
                               ^

回答by Marcin

In general, if you use a stable sorting algorithm, you can just sort by one key, then the next.

通常,如果您使用稳定的排序算法,则可以只按一个键排序,然后再按下一个键排序。

rows.sortBy(_.firstName).sortBy(_.lastName)

The final result will be sorted by lastname, then where that is equal, by firstname.

最终结果将按姓氏排序,然后按名字排序。

回答by spreinhardt

Perhaps this works only for a List of Tuples, but

也许这仅适用于元组列表,但是

scala> var zz = List((1, 0.1), (2, 0.5), (3, 0.6), (4, 0.3), (5, 0.1))
zz: List[(Int, Double)] = List((1,0.1), (2,0.5), (3,0.6), (4,0.3), (5,0.1))

scala> zz.sortBy( x => (-x._2, x._1))
res54: List[(Int, Double)] = List((3,0.6), (2,0.5), (4,0.3), (1,0.1), (5,0.1))

appears to work and be a simple way to express it.

似乎有效并且是一种简单的表达方式。