Jakub Kotur | a425e55 | 2020-12-21 17:28:15 +0100 | [diff] [blame] | 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 | /// |
Joel Galenson | b593e25 | 2021-06-21 13:15:57 -0700 | [diff] [blame] | 9 | /// See [`.into_group_map()`](crate::Itertools::into_group_map) |
Jakub Kotur | a425e55 | 2020-12-21 17:28:15 +0100 | [diff] [blame] | 10 | /// for more information. |
| 11 | pub fn into_group_map<I, K, V>(iter: I) -> HashMap<K, Vec<V>> |
| 12 | where I: Iterator<Item=(K, V)>, |
| 13 | K: Hash + Eq, |
| 14 | { |
| 15 | let mut lookup = HashMap::new(); |
| 16 | |
Joel Galenson | 6f79871 | 2021-04-01 17:03:06 -0700 | [diff] [blame] | 17 | iter.for_each(|(key, val)| { |
| 18 | lookup.entry(key).or_insert_with(Vec::new).push(val); |
| 19 | }); |
Jakub Kotur | a425e55 | 2020-12-21 17:28:15 +0100 | [diff] [blame] | 20 | |
| 21 | lookup |
Joel Galenson | 6f79871 | 2021-04-01 17:03:06 -0700 | [diff] [blame] | 22 | } |
| 23 | |
| 24 | pub fn into_group_map_by<I, K, V>(iter: I, f: impl Fn(&V) -> K) -> HashMap<K, Vec<V>> |
| 25 | where |
| 26 | I: Iterator<Item=V>, |
| 27 | K: Hash + Eq, |
| 28 | { |
| 29 | into_group_map( |
| 30 | iter.map(|v| (f(&v), v)) |
| 31 | ) |
| 32 | } |