Ordered Collections
Sorted maps and sets for Elixir, backed by Erlang trees.
During parental leave, I wanted to spend some time learning more Elixir and Erlang. I looked for something Erlang provided that didn’t have a well-known Elixir equivalent and settled on sorted collections.
Elixir’s Map and MapSet don’t maintain sorted order. Erlang has :gb_trees and :gb_sets, which do. I wrapped them in SortedMap and SortedSet and added support for Elixir’s collection protocols.
alias OrderedCollections.SortedMap
SortedMap.new(%{c: 3, a: 1, b: 2})
|> Enum.to_list()
# => [a: 1, b: 2, c: 3]Working with the collections
SortedMap sorts entries by key. SortedSet keeps unique values in sorted order. Both support range queries, and the set supports union, intersection, and difference.
They implement Enumerable and Collectable, so you can use Enum, Stream, and Enum.into/2. They also implement Inspect for IEx output and the JSON protocol available in Elixir 1.18 and later.
These use Erlang’s term ordering, not insertion order. You can convert them to a regular Map, MapSet, or list, though a regular map or set won’t preserve sorted traversal.
The package is on Hex as ordered_collections. The documentation link above has the full API.