Scala动态列表排序

时间:2014-04-15 17:59:41

标签: scala sorting

我正在寻找一种根据以下要求动态排序列表的简洁方法。

case class Person(name: String, middleName:Option[String], age:Integer) 

现在排序非常简单,但是如果这种排序是由用户进行列排序的UI驱动的,那么传递回服务器的参数就是列名。有关动态创建此排序功能的建议吗?

提前致谢

**更新:

val sortByName = (p :Person) => p.name
val sortByMiddleName = (p: Person) => p.middleName

val mySortMap = Map("name" -> sortByName, "middleName" -> sortByMiddleName)

val sorted = persons.sortBy(mySortMap("name"))

**更新#2

import scala.math.Ordering.Implicits._

type PersonSorter = (Person, Person) => Boolean
val sortByName: PersonSorter = (x:Person, y:Person) => x.name < y.name
// Implicits import takes care of the Option here...
val sortByMiddleName: PersonSorter = (x:Person, y:Person) => x.middleName < y.middleName

val sortingMap: PersonSorter = Map[String, PersonSorter]("name" -> sortByName, "middleName" -> sortByMiddleName)

(排除年龄,但它完全相同)

现在当我有我的清单时,我可以很容易地做到这一点。

persons.sortWith(sortingMap("name"))

其中“name”是从UI传入的参数字符串。

2 个答案:

答案 0 :(得分:2)

这样的事情应该这样做:

scala> val alice = Person("Alice", None, 20)
alice: Person = Person(Alice,None,20)

scala> val bob = Person("Bob", None, 21)
bob: Person = Person(Bob,None,21)

scala> val charlie = Person("Charlie", None, 18)
charlie: Person = Person(Charlie,None,18)

scala> val persons = List(alice, bob, charlie)
persons: List[Person] = List(Person(Alice,None,20), Person(Bob,None,21), Person(Charlie,None,18))

scala> persons.sortBy(p => (p.age, p.name))
res5: List[Person] = List(Person(Charlie,None,18), Person(Alice,None,20), Person(Bob,None,21))

scala> persons.sortBy(p => (p.name, p.age))
res6: List[Person] = List(Person(Alice,None,20), Person(Bob,None,21), Person(Charlie,None,18))

要按参数动态排序,您可以根据作为输入传递的参数定义自己的排序函数。所以你可以写一个函数来返回一个传递给persons.sortBy的函数。传入的函数是排序函数,例如可以sortByAge。如果您需要按两个或更多参数排序,那就是一样的想法。

scala> val sortByAge = (p :Person) => p.age
sortByAge: Person => Integer = <function1>

scala> persons.sortBy(sortByAge)
res9: List[Person] = List(Person(Charlie,None,18), Person(Alice,None,20), Person(Bob,None,21))

答案 1 :(得分:0)

case class Person(name: String, id: Int)
  def sort[T](list: List[T])(compare: (T, T) => Boolean): List[T] = {
    list.sortWith(compare)
  }
  
  
  val list = List(Person("P2", 1), Country("P1", 10))
    val rl = sort(list)((a, b) => a.name < b.name)

这很简单