在Scala中是否有任何方法可以使用变量设置顺序(ASC或DESC)按特定字段对对象列表进行排序?
我知道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)时出现错误。
答案 0 :(得分:2)
您忘记了名字/姓氏案件的(a, b) => expr
部分
case "firstName" => people.sortWith {(a, b) => sortString(a.firstName, b.firstName, sortDirection) }