How to order map by key?

So I have a map:

%{
"num_2" => "some-other-text",
"num_1" => "some-text",
"num_3" => "last-text",
}

The map size always varies, but the key will always have a num_x value. And i want to sort the map by this value. For the example above, the map should then look like this:

%{
"num_1" => "some-text",
"num_2" => "some-other-text",
"num_3" => "last-text",
}

How can I do this?

You can’t with a map. Maps are not ordered. You’d need to convert it to a list if you require ordering.

3 Likes

Kobrakai pretty much covers it, but if you are still looking into it perhaps erlang’s orderedset can come in handy.
If that is not enough but you still need custom order, then AVL Trees may be your best shot (but they will be slower than sets/maps, keep that in mind).

You can find more information about this topic in this forum post:

1 Like