1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You are solution can be even simplified: data.sortBy{ case(k, _) => sortingOrder(k) }
Nice addition I couldn't think of a solution using only sortBy, thank you! Now that you pointed it it seems quite obvious indeed. Feel free to add it as another answer if you want!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.