Idiom #13 Iterate over map keys and values
Access each key k with its value x from an associative array mymap, and print them.

- Ada
- C++
- C++
- C++
- C#
- D
- Dart
- Elixir
- Elixir
- Erlang
- Go
- Groovy
- Haskell
- JS
- JS
- Java
- Java
- Java
- Kotlin
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Perl
- Prolog
- Python
- Python
- Ruby
- Rust
- Scala
- Scala
- Smalltalk
for (auto entry : mymap) {
auto k = entry.first;
auto x = entry.second;
std::cout << k << ": " << x << "\n";
}
for (const auto& kx: mymap) {
std::cout << "Key: " << kx.first << " Value: " << kx.second << std::endl;
}
std::endl flushes stdout.
foreach(var entry in map)
{
Console.WriteLine("Key=" + entry.Key + ", Value=" + entry.Value);
}
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.
K k;
X x;
for (Entry<K, X> e : mymap.entrySet()) {
k = e.getKey();
x = e.getValue();
out.println(e);
}
for i := 1 to mymap.Count do
WriteLn(mymap.Keys[i], '=', mymap.Data[i]);
for (k, x) in &mymap {
println!("Key={key}, Value={val}", key=k, val=x);
}
You can also print collections in a 'nice' way with `println!("{:?}", mymap);` which is the Debug-representation. You can also use "{:#?}" for the pretty version.
This example works the same if you replace BTreeMap with HashMap.
This example works the same if you replace BTreeMap with HashMap.
mymap keysAndValuesDo: [ :k :x |
Transcript cr;
show: 'Key = ', k printString;
show: ', Value = ', x printString]