RRust By Example
intermediateCollections

Group By with HashMap

Group items by key using HashMap.

Group By with HashMap

Group items by key using HashMap.

Difficulty

Intermediate

Code

rust
use std::collections::HashMap;

fn main() {
    let data = vec![
        ("fruit", "apple"),
        ("veggie", "carrot"),
        ("fruit", "banana"),
        ("veggie", "broccoli"),
        ("fruit", "cherry"),
    ];

    let mut groups: HashMap<&str, Vec<&str>> = HashMap::new();
    for (category, item) in data {
        groups.entry(category).or_default().push(item);
    }

    for (category, items) in &groups {
        println!("{}: {:?}", category, items);
    }
}

Explanation

This example demonstrates how to use group by with hashmap in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples