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 createordering
class using methodsordering
companion object:case class myclass(field: int) object myclass { implicit val myclassordering: ordering[myclass] = ordering.by(_.field) }
if
ordering
defined in companion object ofmyclass
, it'll provided sorting automatically. otherwise, you'll have import manually before callingsorted
.ordering
allows provide several different ordering defined on class, , import or provide explicitly 1 want.have class extend
ordered[myclass]
overridingcompare
method. in case necessaryordering
created implicitly.case class myclass(field: int) extends ordered[myclass] { def compare(other: myclass): int = this.field compareto other.field }
this add methods
<
,>
,<=
,>=
class.use
sortby
orsortwith
methods ofvector
, take function , don't needordering
parameter.vectorofmyclass.sortby(_.field) vectorofmyclass.sortwith(_.field < _.field)
Comments
Post a Comment