Elixir converts that map to ordered
iex= %{z: 1, c: 2, k: 3}
result= %{c: 2, k: 3, z: 1}
What i want unordered keys. I found a way with keyword list but i need for maps. Is there a way ?
The fact if the internal representation is ordered or not is an implementation detail. Even though it may be displayed with an ordering, it is still unordered by definition.
In general it’s inadvisable to rely on the ordering of elements in maps, they almost always (meaning in most languages) come with no guarantee that they’ll have consistent ordering.
On the docs page about maps you’ll find the following:
Key-value pairs in a map do not follow any order (that’s why the printed map in the example above has a different order than the map that was created).
there is a topic about that. After 32 keys behaviour changes
As point of view of programmer maps are data structures with no order at all. They got set of keys
and realted to them values
. (If Elixir/Erlang return sorted up to 32 elements, it shouldn’t matter to you at all, as a user of map data structure). Set of keys means any permutation of keys is valid as a return value of method Map.keys(map)
.
You probably don’t want unordered keys if it matters to you that sorted ones are bad.
You are just trying to preserve insert order so you need another data structure for your problem.
I solved with keyword list. For some reason i needed to a key to first key. I wanted map because Poison couldnt convert a keyword list to json. JSON library solved keyword list to json
I wouldn’t rely on this 32 key boundary. The keys are defined to be unordered and this difference in ordering is purely an implementation detail which the OTP team can change whenever they feel like it.
Indeed, just always consider that maps are a standard unordered map as in most languages.
I need it too. how u did it?
Use keyword list
If you need an ordered map, you can try out Aja
’s OrdMap
(disclaimer, I’m the author).
It implements Jason, Enumerable, Access, can be pattern-matched with a macro, and should offer good performance (but with an overhead over a plain map, of course, since it needs to track more information).