Logo

Programming-Idioms

  • Java
  • Python

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 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.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));

Extract keys, sort, iterate.

Keys have type K.
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.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);

The normal iteration of a TreeMap will iterates its key in order.
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());

When mymap implements SortedMap, sorted iteration is straightforward.
for k, x in sorted(mymap.items()):
    print(k, x)
for k in sorted(mymap):
    print(mymap[k])

dictionaries iterate over their keys by default
print(*sorted(mymap.items()))
#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);
}

New implementation...