Fold Accumulates HashMap Group Counts

fold carries a HashMap accumulator to count words and group them by first letter; sorted keys keep the printed output stable across runs.

RustData Integrity

Code

rustsnippet
31 lines
use std::collections::HashMap;

fn main() {
    let words = ["deploy", "test", "deploy", "lint", "test", "deploy"];

    // fold carries a HashMap accumulator; entry + or_insert bumps each count
    let counts: HashMap<&str, usize> =
        words.into_iter().fold(HashMap::new(), |mut acc, word| {
            *acc.entry(word).or_insert(0) += 1;
            acc
        });

    // HashMap iteration order is random; sort keys for stable prints
    let mut names: Vec<&str> = counts.keys().copied().collect();
    names.sort();
    for name in names {
        println!("{name}: {}", counts[name]);
    }

    // the same fold shape builds a grouped index: first letter -> words
    let grouped: HashMap<char, Vec<&str>> =
        words.into_iter().fold(HashMap::new(), |mut acc, word| {
            acc.entry(word.chars().next().unwrap()).or_default().push(word);
            acc
        });
    let mut letters: Vec<char> = grouped.keys().copied().collect();
    letters.sort();
    for letter in letters {
        println!("{letter} -> {:?}", grouped[&letter]);
    }
}

From setup to output — Fold Accumulates HashMap Group Counts

The engine of this file is the function main.

The cycling part of this snippet is for name in names.

What to watch for

  • Built purely on the standard library — nothing to fetch, nothing to link.

Using it

Entry signature: fn main()

Key statements

acc.entry(word.chars().next().unwrap()).or_default().push(word);
let mut letters: Vec<char> = grouped.keys().copied().collect();
let mut names: Vec<&str> = counts.keys().copied().collect();

Interactive Tools for This Topic

FAQ

How do you run Fold Accumulates HashMap Group Counts?
The file is self-contained: run it directly, no dependencies to install beforehand.