| 1 | #![cfg (feature = "use_std" )] |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | use std::hash::Hash; |
| 5 | use std::iter::Iterator; |
| 6 | |
| 7 | /// Return a `HashMap` of keys mapped to a list of their corresponding values. |
| 8 | /// |
| 9 | /// See [`.into_group_map()`](crate::Itertools::into_group_map) |
| 10 | /// for more information. |
| 11 | pub fn into_group_map<I, K, V>(iter: I) -> HashMap<K, Vec<V>> |
| 12 | where |
| 13 | I: Iterator<Item = (K, V)>, |
| 14 | K: Hash + Eq, |
| 15 | { |
| 16 | let mut lookup: HashMap> = HashMap::new(); |
| 17 | |
| 18 | iter.for_each(|(key: K, val: V)| { |
| 19 | lookup.entry(key).or_insert_with(default:Vec::new).push(val); |
| 20 | }); |
| 21 | |
| 22 | lookup |
| 23 | } |
| 24 | |
| 25 | pub fn into_group_map_by<I, K, V>(iter: I, f: impl Fn(&V) -> K) -> HashMap<K, Vec<V>> |
| 26 | where |
| 27 | I: Iterator<Item = V>, |
| 28 | K: Hash + Eq, |
| 29 | { |
| 30 | into_group_map(iter.map(|v: V| (f(&v), v))) |
| 31 | } |
| 32 | |