HashMap Utilities

Common operations for working with HashMaps: merging, filtering, transforming

rust (1.70) 2025-11-12 hashmap collections utility functional

Description

A collection of utility functions for working with Rust HashMaps. Provides common operations like merging maps, filtering entries, and transforming values.

Features

  • Map merging with conflict resolution
  • Entry filtering by key or value
  • Value transformation
  • Key-value swapping

Code

RAW
use std::collections::HashMap;pub fn merge<K, V>(map1: HashMap<K, V>, map2: HashMap<K, V>) -> HashMap<K, V>where    K: std::hash::Hash + Eq + Clone,    V: Clone,{    let mut result = map1;    result.extend(map2);    result}pub fn filter_by_key<K, V, F>(map: HashMap<K, V>, predicate: F) -> HashMap<K, V>where    K: std::hash::Hash + Eq + Clone,    V: Clone,    F: Fn(&K) -> bool,{    map.into_iter()        .filter(|(k, _)| predicate(k))        .collect()}pub fn filter_by_value<K, V, F>(map: HashMap<K, V>, predicate: F) -> HashMap<K, V>where    K: std::hash::Hash + Eq + Clone,    V: Clone,    F: Fn(&V) -> bool,{    map.into_iter()        .filter(|(_, v)| predicate(v))        .collect()}pub fn map_values<K, V, U, F>(map: HashMap<K, V>, f: F) -> HashMap<K, U>where    K: std::hash::Hash + Eq + Clone,    F: Fn(V) -> U,{    map.into_iter().map(|(k, v)| (k, f(v))).collect()}pub fn invert<K, V>(map: HashMap<K, V>) -> HashMap<V, K>where    K: std::hash::Hash + Eq + Clone,    V: std::hash::Hash + Eq + Clone,{    map.into_iter().map(|(k, v)| (v, k)).collect()}
RAW
use hashmap_utils::{merge, filter_by_key, map_values, invert};use std::collections::HashMap;let mut map1 = HashMap::new();map1.insert("a".to_string(), 10);map1.insert("b".to_string(), 20);let mut map2 = HashMap::new();map2.insert("c".to_string(), 30);let merged = merge(map1, map2);let filtered = filter_by_key(merged, |k| k.starts_with("a"));let transformed = map_values(filtered, |v| v * 2);

Comments

No comments yet. Be the first to comment!