How to iterate over a map's key-value pairs in Elixir?
This doesn't work:
my_map = %{a: 1, b: 2, c: 3} Enum.each my_map, fn %{k => v} -> IO.puts "#{k} --> #{v}" end
Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>.
Different ways to iterate through Map : Using keySet(); method and Iterator interface. Using entrySet(); method and for-each loop. Using entrySet(); method and Iterator interface. Using forEach(); in Java 1.8 version.
Turns out you iterate over a Map
exactly like you do over a Keyword List
(i.e. you use a tuple
):
Enum.each %{a: 1, b: 2, c: 3}, fn {k, v} -> IO.puts("#{k} --> #{v}") end
Comprehensions also work:
for {k, v} <- %{a: 1, b: 2, c: 3} do IO.puts("#{k} --> #{v}") end
Note: If you use Enum.map/2
and return a tuple, you'll end up with a Keyword List instead of Map. To convert it into a map, use Enum.into/2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With