scala.collection.mutable.PriorityQueue:比较一个案例的2个或更多属性class

scala.collection.mutable.PriorityQueue: Comparing with 2 or more attributes of a case class

这个问题 Easy idiomatic way to define Ordering for a simple case class 看起来很相似但并不相同。这个问题跟优先级队列比较相关

import scala.collection.mutable.PriorityQueue

  case class Task(prio: Int, text: String, jobPriority:Int)
    extends Ordered[Task] {
    def compare(that: Task) = that.prio compare this.prio
   // def compare(x: Task, y: Task) = y.prio compare this.prio //&&  y.jobPriority compare this.jobPriority

  }

  //test
  var q: mutable.PriorityQueue[Task] = PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains",1), Task(4, "Feed cat",2),
    Task(5, "Make tea",9), Task(1, "Solve RC tasks",5), Task(2, "Tax return",5))
  while (q.nonEmpty) println(q dequeue)

给我这个输出:

Task(1,Solve RC tasks,5)
Task(2,Tax return,5)
Task(3,Clear drains,1)
Task(4,Feed cat,2)
Task(5,Make tea,9)

现在我在做比较的时候也想考虑jobPriority。就像比较多个属性的自定义 java 比较器一样。

scala 中有什么方法可以实现这个吗?

你可以这样做:

case class Task(prio: Int, text: String, jobPriority:Int)
    extends Ordered[Task] {
    def prioCompare(that: Task) = that.prio compare this.prio
    def jobPriorityCompare(that: Task) = that.jobPriority compare this.jobPriority
    def compare(that: Task) = {
      val prioC = prioCompare(that)

      if(prioC == 0) jobPriorityCompare(that) else prioC
    }

  }

  //test
  var q: mutable.PriorityQueue[Task] = PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains",6), Task(4, "Feed cat",2),
    Task(5, "Make tea",9), Task(1, "Solve RC tasks",5), Task(3, "Tax return",5))
  while (q.nonEmpty) println(q dequeue)

/* Output
Task(1,Solve RC tasks,5)
Task(3,Tax return,5)
Task(3,Clear drains,6)
Task(4,Feed cat,2)
Task(5,Make tea,9)
*/

与元组比较:

import scala.collection.mutable.PriorityQueue

  case class Task(prio: Int, text: String, jobPrio: Int)
    extends Ordered[Task] {

    import scala.math.Ordered.orderingToOrdered

    def compare(that: Task) = (that.prio, that.jobPrio) compare(this.prio, this.jobPrio)

  }

  //test
  var q: mutable.PriorityQueue[Task] = PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains", 1), Task(4, "Feed cat", 2),
    Task(5, "Make tea", 9), Task(1, "Solve RC tasks", 5), Task(2, "Tax return", 5))
  while (q.nonEmpty) println(q dequeue)

结果:

Task(1,Solve RC tasks,5)
Task(2,Tax return,5)
Task(3,Clear drains,1)
Task(4,Feed cat,2)
Task(5,Make tea,9)