Logo

Programming-Idioms

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.

import "fmt"
import "golang.org/x/exp/maps"
import "slices"
keys := maps.Keys(mymap)
slices.Sort(keys)

for _, k := range keys {
	x := mymap[k]
	fmt.Println("Key =", k, ", Value =", x)
}
import "fmt"
import "golang.org/x/exp/maps"
import "slices"
keys := maps.Keys(mymap)
slices.SortFunc(keys, compare)

for _, k := range keys {
	x := mymap[k]
	fmt.Println("Key =", k, ", Value =", x)
}
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)
}
#include <iostream>
#include <map>
std::map< K, V > _mymap;
for (const auto& pair : _mymap) {
    std::cout << pair.first << ": " << pair.second << "\n";
}
#include <map>
#include <iostream>
#include <string>
auto print(auto&... args) {
  // c++17 fold expression
  (std::cout << ... << args) << std::endl;
}

auto print_map_contents(auto mymap) {
  // c++17 structured binding
  for (auto [k, x] : mymap) {
    print("mymap[", k, "] = ", x);
  }
}

auto main() -> int {
  // map is ordered map, iteration is ascending by key value
  auto map = std::map<std::string, int> {
    {"first entry", 12},
    {"second entry", 42},
    {"third entry", 3},
  };

  print_map_contents(map);
}
using System.Collections.Generic;
SortedDictionary<string, string> myMap;
foreach (var item in myMap)
{
  Console.WriteLine($"{item.Key}={item.Value}");
}
	
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));
var sortedKeys = myMap.keys.toList()..sort();
for (var k in sortedKeys) {
  print("Key=$k Value=${myMap[k]}");
}
mymap.sort { it.key }.each { println it}
import Data.Map as Map
mapM_ print (Map.toList mymap)
[...mymap.entries()].sort().map(([_, x]) => console.log(x))
import java.util.Map;
import java.util.TreeMap;
var map = Map.of("a", 1, "d", 4, "c", 3, "b", 2);
new TreeMap<>(map).entrySet().forEach(System.out::println);
import static java.lang.System.out;
import java.util.Map.Entry;
import java.util.TreeMap;
for (Entry<K, V> e : new TreeMap<>(m).entrySet())
    out.println(e);
import java.util.Map.Entry;
mymap.entrySet().stream().sorted(Entry.comparingByKey()).forEach(System.out::println);
import static java.lang.System.out;
import static java.util.Map.Entry.comparingByKey;
mymap.entrySet()
    .stream()
    .sorted(comparingByKey())
    .forEach(e -> {
        K k = e.getKey();
        X x = e.getValue();
        out.println(e);
    });
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));
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());
for k, x in pairs(mymap) do
  print(k, x)
end
ksort($mymap);
foreach($mymap as $k => $v) {
    echo 'k:', $k, ' ', 'v:', $v, PHP_EOL;
}
use 5.010;
for my $k (sort keys %mymap) {
    my $x = $mymap{$k};
    say "$k => $x";
}
dict_pairs(D, _, Ps),
forall(member(K-V, Ps),
       format("~w:~w~n", [K, V]))
for e in sorted(m.items()):
    print(e)
for k in sorted(mymap):
    print(mymap[k])
my_map.sort.each{|k,x| puts "#{k}: #{x}"}
for (k, x) in mymap {
    println!("({}, {})", k, x);
}
import scala.collection.immutable.SortedMap
SortedMap.from(mymap).foreach{ case (k, x) => println(s"$k => $x") }

New implementation...