CodingNeed.

3 · Reliability and project · 25 MIN

Iterators, vectors and map entries

Iterator adapters describe work; a consumer performs it.

filter creates a lazy adapter and collect consumes it to build a new collection. The source vector remains borrowed while iteration proceeds. A HashMap entry gives one place to handle both inserting a missing key and modifying an existing value. HashMap order is unspecified, so the example checks a named entry instead of relying on printed iteration order. Keep numeric overflow and case-normalization rules explicit before using a frequency counter on arbitrary text.

Use entry for updates and a separate sorted key list for presentation.

Read the example

use std::collections::HashMap;
fn main() {
    let values = vec![1,2,2,3];
    let evens: Vec<i32> = values.iter().copied().filter(|n| n % 2 == 0).collect();
    let mut counts = HashMap::new();
    for value in &values { *counts.entry(*value).or_insert(0_u32) += 1; }
    println!("{:?}", evens);
    println!("{}", counts[&2]);
    println!("{}", values.len());
}
Check the expected output
[2, 2]
2
4

Your challenge

Build a case-sensitive word-frequency function returning a HashMap and render sorted keys for a stable report.

Solution cost: Expected O(n) counting with O(k) distinct-key storage. time · Account for collection storage separately from the returned result. space

Common trap

An iterator that is never consumed does not execute its transformation pipeline.

Study the project implementation
use std::collections::HashMap;
fn main() {
    let values = vec![1,2,2,3];
    let evens: Vec<i32> = values.iter().copied().filter(|n| n % 2 == 0).collect();
    let mut counts = HashMap::new();
    for value in &values { *counts.entry(*value).or_insert(0_u32) += 1; }
    println!("{:?}", evens);
    println!("{}", counts[&2]);
    println!("{}", values.len());
}

Further reading: Official documentation

Next lesson: Project · A checked expense total

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.