sorting - How can i sort a Vector of objects in Scala? -
i have vector of objects of particular class. how can sort them? comparison method must add class make sortable? if not method, ordering function should implement?
method sorted of vector takes implicit parameter of type math.ordering[b], uses sorting. there several ways provide it:
define implicit
math.ordering[myclass]. can createorderingclass using methodsorderingcompanion object:case class myclass(field: int) object myclass { implicit val myclassordering: ordering[myclass] = ordering.by(_.field) }if
orderingdefined in companion object ofmyclass, it'll provided sorting automatically. otherwise, you'll have import manually before callingsorted.orderingallows provide several different ordering defined on class, , import or provide explicitly 1 want.have class extend
ordered[myclass]overridingcomparemethod. in case necessaryorderingcreated implicitly.case class myclass(field: int) extends ordered[myclass] { def compare(other: myclass): int = this.field compareto other.field }this add methods
<,>,<=,>=class.use
sortbyorsortwithmethods ofvector, take function , don't needorderingparameter.vectorofmyclass.sortby(_.field) vectorofmyclass.sortwith(_.field < _.field)
Comments
Post a Comment