scala.collection.mutable.PriorityQueue:与案例类的 2 个或更多属性进行比较
Posted
技术标签:
【中文标题】scala.collection.mutable.PriorityQueue:与案例类的 2 个或更多属性进行比较【英文标题】:scala.collection.mutable.PriorityQueue: Comparing with 2 or more attributes of a case class 【发布时间】:2019-10-30 22:10:10 【问题描述】:这个问题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 有什么方法可以实现这个吗?
【问题讨论】:
这能回答你的问题吗? Easy idiomatic way to define Ordering for a simple case class 它仍然是重复的。根据您接受的答案,链接的问题是您问题的准确答案。 【参考方案1】:你可以这样做:
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)
*/
【讨论】:
这可能有效。但链接的问题提供了更惯用的解决方案。【参考方案2】:与元组比较:
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)
【讨论】:
以上是关于scala.collection.mutable.PriorityQueue:与案例类的 2 个或更多属性进行比较的主要内容,如果未能解决你的问题,请参考以下文章
Spark Scala Error: java.lang.NoSuchMethodError: scala.collection.mutable.Buffer$.empty()Lscalacollec
spark提示Caused by: java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot b