Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a Map's key-value pairs

Tags:

elixir

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 
like image 338
Sheharyar Avatar asked Oct 08 '16 22:10

Sheharyar


People also ask

How would you iterate over the key value pairs from an instance of map?

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>.

How do I iterate over a map string Arraylist object >>?

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.


1 Answers

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.

like image 172
Sheharyar Avatar answered Sep 20 '22 12:09

Sheharyar