Logo

Programming-Idioms

  • Go
  • D

Idiom #13 Iterate over map keys and values

Access each key k with its value x from an associative array mymap, and print them.

Traversing each key and each associated object of mymap
import std.stdio;
int[string] mymap = ["Hello":1 , "World":2];
foreach (k, v; mymap)
    writeln("Key: ", k, " Value: ", v);

D has built-in associative array
import "fmt"
for k, x := range mymap {
  fmt.Println("Key =", k, ", Value =", x)
}

Do not rely on the order of the traversal ! The order is undefined and is intentionaly randomized by the Go runtime.
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;

use Ada.Containers;
for C in My_Map.Iterate loop
   Put_Line ("Key = " & Key (C) & ", Value = " & Element (C));
end loop;

New implementation...