Scala由多个字段排序

时间:2012-05-15 14:17:05

标签: scala

这个问题可能很愚蠢,但我找不到一个例子,也无法弄明白。

我想按顺序比较两个Person类的最后,第一和中间名。这是做死脑筋的方法:

def compare(that: Person): Int = {
  val last: Int = lastName.compare(that.lastName)
  if (last != 0) last
  else {
    val first: Int = firstName.compare(that.firstName)
    if (first != 0) first
    else middleName.compare(that.middleName)
}

我知道有一些更聪明的方法可以做到这一点(可能使用Ordering),但我不能指责它。

托德

一旦我意识到如何在订购中访问正确的东西,我就想出了这个。

def compare(that: Person): Int = {
  Ordering.Tuple3(Ordering.String, Ordering.String, Ordering.String).compare(
     (lastName, firstName, middleName),
     (that.lastName, that.firstName, that.middleName))
}

我很确定我能用更少的语言来解决这个问题,但这种方法很有效,并且相当紧凑。

2 个答案:

答案 0 :(得分:16)

选项1:sortBy

使用sortBy方法,这可能非常简单:

case class Person(first: String, middle: String, last: String)
val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sortBy{ case Person(f,m,l) => (l,f,m) } 

选项2:扩展有序[人]

通过扩展Ordered[Person],该课程将了解如何对自己进行排序,因此我们可以免费获得sortedminmax等内容:

case class Person(first: String, middle: String, last: String) extends Ordered[Person] {
  def compare(that: Person): Int =
    (last compare that.last) match {
      case 0 => 
        (first compare that.first) match {
          case 0 => middle compare that.middle
          case c => c
        }
      case c => c
    }
}

val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sorted
personList.min
personList.max

选项3:隐式排序

如果您使用隐式Ordering,则会获得sortedmin等,而不会将该特定顺序与原始类绑定。这种解耦可能很方便,也可能很烦人,具体取决于你的具体情况。

case class Person(first: String, middle: String, last: String)

implicit val ord = new Ordering[Person] { 
  def compare(self: Person, that: Person): Int =
    (self.last compare that.last) match {
      case 0 => 
        (self.first compare that.first) match {
          case 0 => self.middle compare that.middle
          case c => c
        }
      case c => c
    }
}

val personList = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))
personList.sorted
personList.min
personList.max

答案 1 :(得分:0)

您还可以使用Ordering.byorElseBy。这很明确。

case class Person(first: String, middle: String, last: String)

implicit val ordering: Ordering[Person] = Ordering.by[Person, String](_.first)
   .orElseBy(_.middle)
   .orElseBy(_.last)

val list = List(Person("john", "a", "smith"), Person("steve", "x", "scott"), Person("bill", "w", "smith"))

list.sorted