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:

  1. define implicit math.ordering[myclass]. can create ordering class using methods ordering companion object:

    case class myclass(field: int) object myclass {   implicit val myclassordering: ordering[myclass] = ordering.by(_.field) } 

    if ordering defined in companion object of myclass, it'll provided sorting automatically. otherwise, you'll have import manually before calling sorted. ordering allows provide several different ordering defined on class, , import or provide explicitly 1 want.

  2. have class extend ordered[myclass] overriding compare method. in case necessary ordering created implicitly.

    case class myclass(field: int) extends ordered[myclass] {   def compare(other: myclass): int = this.field compareto other.field } 

    this add methods <, >, <=, >= class.

  3. use sortby or sortwith methods of vector, take function , don't need ordering parameter.

    vectorofmyclass.sortby(_.field) vectorofmyclass.sortwith(_.field < _.field) 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -