This language bar is your friend. Select your favorite languages!

Idiom #112 Iterate over map entries, ordered by keys

Print each key k with its value x from an associative array mymap, in ascending order of k.

for (k, x) in mymap {
    println!("({}, {})", k, x);
}
import std.algorithm;
import std.array;
import std.stdio;
mymap.byKeyValue
     .array
     .sort!((a, b) => a.key < b.key)
     .each!(p => writeln(p.key, " ", p.value));
import "fmt"
import "sort"
keys := make([]string, 0, len(mymap))
for k := range mymap {
	keys = append(keys, k)
}
sort.Strings(keys)

for _, k := range keys {
	x := mymap[k]
	fmt.Println("Key =", k, ", Value =", x)
}
import Data.Map as Map
mapM_ print (Map.toList mymap)
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
SortedMap<K, V> mymap = new TreeMap<>();
...
for(Map.Entry<K, V> e: mymap.entrySet())
	System.out.println("Key=" + e.getKey() + ", Value=" + e.getValue());
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
List<K> keys = new ArrayList<>(mymap.keySet());
Collections.sort(keys);
for(K k: keys)
	System.out.println("Key=" + k + ", Value=" + mymap.get(k));
ksort($mymap);
foreach($mymap as $k => $v) {
    echo 'k:', $k, ' ', 'v:', $v, PHP_EOL;
}
dict_pairs(D, _, Ps),
forall(member(K-V, Ps),
       format("~w:~w~n", [K, V]))
for k in sorted(mymap.keys()):
    print(k)
my_map.sort.each{|k,x| puts "#{k}: #{x}"}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms