RUST / CHAPTER 09

Hash maps and entry-based aggregation

Intermediate

Accumulate keyed data without losing existing values.

By the end of this chapter

  • Use entry for counting
  • Distinguish absent keys from stored zero
  • Separate storage order from presentation order

The idea

HashMap stores values under hashable keys. get returns an Option because a key may be absent; a stored zero is still a present value. The entry API combines lookup with insertion when necessary, avoiding a separate search-and-update pattern. or_insert returns a mutable reference to the existing or newly inserted value, so incrementing through that reference updates the map entry.

Hash-map iteration does not provide a sorted output contract. Collect and sort keys or use an ordered data structure when presentation order matters. Ownership still applies to inserted keys and values: moving a String key into a map transfers ownership, while borrowed lookups can often avoid another allocation. State whether an aggregation keeps empty groups, negative totals, and zero totals so the algorithm does not discard meaningful results.

Rust example
use std::collections::HashMap;
fn main(){ let mut counts=HashMap::new(); for word in ["red","blue","red"] {*counts.entry(word).or_insert(0)+=1;} println!("{}",counts["red"]); println!("{}",counts.contains_key("green")); }
Result
2
false

The first red inserts zero before incrementing; the second red updates the existing count.

Try it yourself

Count labels and print their totals in sorted label order, including any legitimate zero total.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What remains in m["a"] after this code?
let mut m=HashMap::from([("a",4)]);
*m.entry("a").or_insert(10)+=2;