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

Group data by key using entry().or_default().push().

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

More Collections Examples