1
Scala中有没有什么方法可以通过特定的字段使用变量来排列对象列表来设置顺序(ASC或DESC)?根据Scala中的变量进行排序
我知道有sortWith你可以这样做
myList.sortWith((x, y) => x < y)
或
myList.sortWith((x, y) => x > y)
排序升序或降序,但我想用一个变量。
所以,我想是这样的:
case class Person(firstName: String, LastName: String, age: Int)
private def sortDocuments(sortField: String, sortDirection: String, people: List[Person]): List[Person] = {
sortField match {
case "age" => people.sortBy(if (sortDirection == "desc") -_.age else _.age)
case "firstName" => people.sortWith { sortString(a.firstName, b.firstName, sortDirection) }
case "lastName" => people.sortWith { sortString(a.firstName, b.lastName, sortDirection) }
}
}
private def sortString(fieldA: String = null, fieldB: String = null, direction: String = "asc") = {
val fieldAVaild = Option(fieldA).getOrElse("")
val fieldBVaild = Option(fieldB).getOrElse("")
if (direction == "desc") fieldBVaild > fieldAVaild else fieldAVaild < fieldBVaild
}
但sortWith只接收的功能有两个参数,所以我得到一个错误,当我添加了第三个参数(sortDirection)。
你可能想看看sortBy,这应该足以满足你的使用情况,并易于使用的
(a, b) => expr
部分。 –