Search code examples
scalasortingsqueryl

How to sort list in Scala by specific values


I'm using squeryl and I have a list (query.toList) of classes. The classes have a property ("status") I want to sort on, but I want to sort on an ordering I decide that is not alphabetical or numerical. For example if there was a list of 3 classes:

(<Foo1>, <Foo2>, <Foo3>)

And Foo1.status was suspended, Foo2 was approved, and Foo3 is rejected, after sorting it'd become:

(<Foo2>, <Foo3>, <Foo1>)

I want approved always first, suspended always last, rejected after approved, etc. Just arbitrary ordering. I'm not sure how to do this nicely. I can do multiple queries and manually build it like get all approved, then get all rejected and append to that list, get all suspended append, and so on but that seems super heavy


Solution

  • You should use sortBy. You can then either implement a custom Ordering[Status], or just convert your statuses to some other type (like an int) that sorts naturally. For instance:

    list.sortBy { f =>
      f.status match {
        case Approved => 0
        case Rejected => 1
        case Suspended => 2
      }
    }