Scala动态列表排序 [英] Scala dynamic list sorting
问题描述
我正在寻找一种符合以下要求的动态排序列表的干净方法.
I'm looking for a clean way of dynamically sorting a list with the following requirements.
case class Person(name: String, middleName:Option[String], age:Integer)
现在排序非常简单,但是,如果将这种排序从UI驱除,则用户将在其中进行列排序,而传递回服务器的参数将仅仅是列名.有什么建议可以动态创建此排序功能?
Now sorting that is pretty straight forward however if this sort is driven off a UI where a user would do column sorting and the parameters passed back to the server would simply be the column name. Any suggestions to dynamically create this sorting capability?
预先感谢
**已更新:
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)
(排除年龄,但完全一样)
(Excluded age, but it's the exact same thing)
现在,当我有清单时,我可以轻松地做到这一点.
Now when I have my list, I can easily just do this.
persons.sortWith(sortingMap("name"))
其中名称"是从用户界面传入的参数字符串.
Where "name" is a parameter string passed in from the UI.
推荐答案
应该执行以下操作:
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
进行排序.如果您需要按两个或多个参数进行排序,这是相同的想法.
To dynamically sort by parameters you can define you own sort functions based on the parameters passed as input. So you could write a function that returns a function that is passed into persons.sortBy
. That function passed in is the sorting function which could by sortByAge
for example. It's the same idea if you need to sort by two or more parameters.
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))
这篇关于Scala动态列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!