Logo

Programming-Idioms

  • Dart
  • Java

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
for (Map.Entry<Object, Object> entry : mymap.entrySet()) {
    Object k = entry.getKey();
    Object x = entry.getValue();
    System.out.println("Key=" + k + ", Value=" + x);
}

Instead of Object, consider using sensible key type and value type for your map.
import java.util.Map;
mymap.forEach((k,x) -> System.out.println("Key=" + k + ", Value=" + x));
import static java.lang.System.out;
import java.util.Map.Entry;
K k;
X x;
for (Entry<K, X> e : mymap.entrySet()) {
    k = e.getKey();
    x = e.getValue();
    out.println(e);
}
mymap.forEach((k, v) => print('Key=$k, Value=$v'));
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...