How to combine all keys and values from a HashMap into a single string in Rust

1 Answer

0 votes
use std::collections::HashMap;

fn combine_keys_and_values(data: HashMap<String, String>) -> String {
    data.into_iter()
        .map(|(key, value)| format!("{}={}", key, value))
        .collect::<Vec<String>>()
        .join(", ")
}

fn main() {
    let mut data = HashMap::new();
    
    data.insert("Key1".to_string(), "Value1".to_string());
    data.insert("Key2".to_string(), "Value2".to_string());
    data.insert("Key3".to_string(), "Value3".to_string());
    data.insert("Key4".to_string(), "Value4".to_string());

    let combined_string = combine_keys_and_values(data);

    println!("Combined keys and values: {}", combined_string);
}



      
/*
run:

Combined keys and values: Key4=Value4, Key1=Value1, Key3=Value3, Key2=Value2
     
*/

 



answered Apr 1, 2025 by avibootz
...