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

时间:2012-04-05 11:16:41

标签: scala sorting functional-programming

如何在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)

我尝试这样的事情

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

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

4 个答案:

答案 0 :(得分:194)

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

答案 1 :(得分:11)

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

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

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

如果你想先按lastName排序,那么firstName;与较长的名字相关(Wild,Wilder,Wilderman)。

如果你写

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

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

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

答案 2 :(得分:6)

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

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

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

答案 3 :(得分:-3)

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

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))

似乎有效并且是表达它的简单方法。