如何在Scala中按两个字段sorting列表?

如何在Scala中对两个字段进行sorting,在这个例子中,我将按lastName和firstNamesorting?

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) 

但它不起作用。 所以我对一个好的和简单的解决scheme感到好奇。

提前致谢!

猩猩

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

如果你想通过合并的名称进行sorting,就像在你的问题中那样

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

如果你首先要按姓氏sorting,那么firstName; 与更长的名字有关(Wild,Wilder,Wilderman)。

如果你写

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

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

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

一般来说,如果你使用稳定的sortingalgorithm,你可以按一个键,然后下一个。

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

最后的结果将按姓氏sorting,然后按名字sorting。

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

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

似乎工作,并成为一个简单的方式来expression它。