BeginnerLesson 6 of 155 min read

Vec, HashMap and Iterators

Store readings in a Vec, count and group with a HashMap, and use iterator chains such as map, filter, fold, zip and windows, with every result verified in Python.

In this lesson you will

  • Use Vec and slices
  • Count and group with HashMap
  • Chain iterator adapters
  • Make HashMap output deterministic

About 28 minutes

Many readings, many questions

Ines has a day of hourly wind readings from three turbines and wants to know the average, the highest value, how many readings each turbine delivered and which hours rose by more than three metres per second. Rust’s collections and iterators answer all of these concisely. A Vec is a growable array that owns its elements, a slice &[T] is a borrowed view of part of one, and a HashMap maps keys to values. The entry API is the idiomatic way to insert or update: map.entry(key).or_insert(0) gives a mutable reference that you can increase.

Iterators are lazy: iter(), map and filter do nothing until a consuming method such as sum, collect, count or fold runs the chain. The compiler turns such chains into machine code as fast as hand-written loops, which Rust calls a zero-cost abstraction. A HashMap’s iteration order is deliberately randomised in every run for security reasons, so when output must be reproducible, collect the entries into a Vec and sort it first, as the example does.

Need Tool
Add an element v.push(x)
Borrowed part &v[1..4]
Count per key *map.entry(k).or_insert(0) += 1
Transform .iter().map(|x| …)
Keep some .filter(|x| …)
Reduce .fold(0, |a, x| a + x)
Pairs of neighbours .windows(2)
use std::collections::HashMap;

fn main() {
    let readings: Vec<(&str, f64)> = vec![
        ("north", 8.5), ("south", 12.0), ("north", 9.5), ("east", 4.0),
        ("south", 15.5), ("north", 14.0), ("east", 4.5), ("south", 11.0),
    ];
    let speeds: Vec<f64> = readings.iter().map(|(_, s)| *s).collect();
    let total: f64 = speeds.iter().sum();
    let max = speeds.iter().cloned().fold(f64::MIN, f64::max);
    println!("{} readings, total {}, mean {:.3}, max {}", speeds.len(), total, total / speeds.len() as f64, max);
    let mut counts: HashMap<&str, u32> = HashMap::new();
    let mut sums: HashMap<&str, f64> = HashMap::new();
    for (name, s) in &readings {
        *counts.entry(name).or_insert(0) += 1;
        *sums.entry(name).or_insert(0.0) += s;
    }
    let mut names: Vec<&&str> = counts.keys().collect();
    names.sort();
    for n in names {
        println!("{:<6} count {} mean {:.2}", n, counts[*n], sums[*n] / counts[*n] as f64);
    }
    let rises: Vec<f64> = speeds.windows(2).map(|w| w[1] - w[0]).filter(|d| *d > 3.0).collect();
    println!("rises above 3: {:?}", rises);
    let strong: Vec<String> = readings.iter().filter(|(_, s)| *s >= 12.0).map(|(n, s)| format!("{}:{}", n, s)).collect();
    println!("strong: {}", strong.join(", "));
    let mut sorted = speeds.clone();
    sorted.sort_by(|a, b| b.partial_cmp(a).unwrap());
    println!("top three: {:?} | first slice: {:?}", &sorted[..3], &speeds[1..3]);
    let paired: Vec<(f64, f64)> = speeds.iter().cloned().zip(speeds.iter().skip(1).cloned()).take(2).collect();
    println!("zip: {:?} | any over 15? {} | all positive? {}", paired, speeds.iter().any(|&s| s > 15.0), speeds.iter().all(|&s| s > 0.0));
}
8 readings, total 79, mean 9.875, max 15.5
east   count 2 mean 4.25
north  count 3 mean 10.67
south  count 3 mean 12.83
rises above 3: [3.5, 11.5, 6.5]
strong: south:12, south:15.5, north:14
top three: [15.5, 14.0, 12.0] | first slice: [12.0, 9.5]
zip: [(8.5, 12.0), (12.0, 9.5)] | any over 15? true | all positive? true

The eight readings gave a total of 79, a mean of 9.875 and a maximum of 15.5. The HashMap counted per turbine with the entry API, and since the map’s own order changes between runs, the keys were collected and sorted before printing, which gave this reproducible list: east 2 readings with mean 4.25; north 3 readings with mean 10.67; south 3 readings with mean 12.83.

The windows(2) call looked at each pair of neighbouring readings, and only the rises of more than 3 were kept: 3.5, 11.5, 6.5. The filter and map chain selected the strong readings, south:12, south:15.5, north:14, the sorted copy gave the top three as 15.5, 14.0, 12.0, and the slice &speeds[1..3] borrowed elements 1 and 2, 12.0, 9.5, without copying anything. The zip of the list with itself shifted by one made neighbouring pairs, and any and all answered yes/no questions in one line, with results true and true.

Notice that the code never wrote an index loop, so it cannot read past the end, and that the floating-point maximum used fold with f64::max, since f64 does not implement Ord because of NaN, and the sort used partial_cmp for the same reason. These are not quirks but honest modelling: NaN has no place in an ordering, and Rust makes you say what to do about it.

Check by hand: Python summed the same eight values to 79, divided by 8, and got 9.875. The south readings are 12.0, 15.5 and 11.0, whose mean is 38.5/3 = 12.83, and the rises were computed from the neighbouring differences of the list in Python and agree.

Never rely on HashMap order

The order is different in every run. Sort the keys, or use a BTreeMap, which keeps keys sorted, when you need a stable output, for example in tests and reports.

Prefer iterators to index loops

An iterator chain cannot go out of bounds, says what it does, and is compiled to an equally fast loop. Reach for indexes only when you need the position itself.

About this course

Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording.

Practice

Use a BTreeMap instead of the HashMap and remove the sort. Compute the median of the speeds by sorting a copy. Group the readings into the four classes from lesson 4 with entry and count them.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does the entry API do?

  1. Removes a key
  2. Sorts the map
  3. Inserts or updates a value by key
  4. Clones the map

entry(k).or_insert(v).

Why sort HashMap keys before printing?

  1. They are unsorted for speed only
  2. Iteration order changes between runs
  3. Rust requires it
  4. To save memory

The order is randomised.

When does an iterator chain run?

  1. When it is created
  2. When a consuming method such as sum or collect is called
  3. At compile time
  4. Never

Iterators are lazy.

What does windows(2) give?

  1. Overlapping pairs of neighbours
  2. Two halves
  3. Two copies
  4. The first two

Useful for differences.

Why can’t f64 be sorted with sort()?

  1. It is not Ord because of NaN
  2. It is too big
  3. It is unsigned
  4. It is a reference

Use sort_by with partial_cmp.

Summary

  • Vec owns a growable array; a slice borrows part of one.
  • HashMap with the entry API counts and groups; sort for stable output.
  • Iterator chains are lazy and run when consumed.
  • f64 needs partial_cmp or f64::max because of NaN.

Next lesson

Lesson 7 is a project: turbine statistics, verified against Python.

Questions

Vec or array?

An array has a size fixed at compile time. A Vec can grow and lives on the heap. Use a Vec unless the size is truly fixed.

What is a slice?

A borrowed view of a contiguous part of an array or Vec, written &[T], carrying a pointer and a length.

Are iterators slow?

No. The compiler usually produces code as fast as a hand-written loop. Measure with a release build if it matters.

Progress is saved in this browser.