How to sort an array with a custom order in Scala

Viewed 97

I have a collection of data like the following:

val data = Seq(
  ("M",   1),
  ("F",   2),
  ("F",   3),
  ("F/M", 4),
  ("M",   5),
  ("M",   6),
  ("F/M", 7),
  ("F",   8)
)

I would like to sort this array according to the first value of the tuple. But I don't want to sort them in alphabetic order, I want them to be sorted like that: all Fs first, then all Ms and finally all F/Ms (I don't are about the inner sorting for values with the same key).

I thought about extending the Ordering class, but it feel quite overkilling for such a simple problem. Any idea?

1 Answers

EDIT: See @Eastsun's comment below for an even simpler solution.

I finally came up with a simple solution based on a map:

val sortingOrder = Map("F" -> 0, "M" -> 1, "F/M" -> 2)
data.sortWith((p1, p2) => sortingOrder(p1._1) < sortingOrder(p2._1))

This will of course fail if there is a unknown key in data, but it will be fine in my case.

In order to avoid an error when a new key is met, we can do the following:

val sortingOrder = Map("F" -> 0, "M" -> 1, "F/M" -> 2)
val nKeys = sortingOrder.size
data.sortWith((p1, p2) => sortingOrder.getOrElse(p1._1, nKeys) < sortingOrder.getOrElse(p2._1, nKeys))

This will push tuples with unknown keys at the end of the list.

Related