🔁 Iteration

Iterating Hash Maps

Loop over keys, values, or both at the same time

After building a map in one pass, you often need to iterate over it. The syntax varies a lot across languages.

Language:
Python
Loading...

All languages — Keys and Values

JavaScript
const freq = { a: 3, b: 1, c: 2 };

// Keys + Values:
for (const [key, value] of Object.entries(freq)) {
  console.log(key, value);
}

// Nur Keys:
for (const key of Object.keys(freq)) {
  console.log(key);
}

// Nur Values:
for (const value of Object.values(freq)) {
  console.log(value);
}
TypeScript
const freq: Record<string, number> = { a: 3, b: 1, c: 2 };

for (const [key, value] of Object.entries(freq)) {
  console.log(key, value);
}
Java
Map<String, Integer> freq = new HashMap<>();
freq.put("a", 3); freq.put("b", 1); freq.put("c", 2);

// Keys + Values:
for (Map.Entry<String, Integer> entry : freq.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}

// Kurzform (Java 8+):
freq.forEach((k, v) -> System.out.println(k + " " + v));
Go
freq := map[string]int{"a": 3, "b": 1, "c": 2}

for key, value := range freq {
    fmt.Println(key, value)
}

// Nur Keys:
for key := range freq {
    fmt.Println(key)
}
C++
unordered_map<string,int> freq = {{"a",3},{"b",1},{"c",2}};

// Keys + Values:
for (auto& [key, value] : freq) {
    cout << key << " " << value << endl;
}

// C++11 Alternativ:
for (auto it = freq.begin(); it != freq.end(); ++it) {
    cout << it->first << " " << it->second << endl;
}