Skip to content

Commit 600b91c

Browse files
bors[bot]Sagebati
andauthored
Merge #406
406: Into_group_map_by r=jswrenn a=Sagebati Add the into_group_map_by , tried with returning an iterator instead of an hashmap, can ben reverted on demand. Co-authored-by: Samuel Batissou <[email protected]> Co-authored-by: Samuel Batissou Tiburcio <[email protected]>
2 parents ca8df94 + bdc4652 commit 600b91c

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/group_map.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,16 @@ pub fn into_group_map<I, K, V>(iter: I) -> HashMap<K, Vec<V>>
1919
}
2020

2121
lookup
22-
}
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+
}
33+
34+

src/lib.rs

+36
Original file line numberDiff line numberDiff line change
@@ -2328,6 +2328,42 @@ pub trait Itertools : Iterator {
23282328
group_map::into_group_map(self)
23292329
}
23302330

2331+
2332+
/// Return an `Iterator` on a HahMap. Keys mapped to `Vec`s of values. The key is specified in
2333+
/// in the closure.
2334+
/// Different of into_group_map_by because the key is still present. It is also more general.
2335+
/// you can also fold the group_map.
2336+
///
2337+
/// ```
2338+
/// use itertools::Itertools;
2339+
/// use std::collections::HashMap;
2340+
///
2341+
/// let data = vec![(0, 10), (2, 12), (3, 13), (0, 20), (3, 33), (2, 42)];
2342+
/// let lookup: HashMap<u32,Vec<(u32, u32)>> = data.clone().into_iter().into_group_map_by(|a|
2343+
/// a.0);
2344+
///
2345+
/// assert_eq!(lookup[&0], vec![(0,10),(0,20)]);
2346+
/// assert_eq!(lookup.get(&1), None);
2347+
/// assert_eq!(lookup[&2], vec![(2,12), (2,42)]);
2348+
/// assert_eq!(lookup[&3], vec![(3,13), (3,33)]);
2349+
///
2350+
/// assert_eq!(
2351+
/// data.into_iter()
2352+
/// .into_group_map_by(|x| x.0)
2353+
/// .into_iter()
2354+
/// .map(|(key, values)| (key, values.into_iter().fold(0,|acc, (_,v)| acc + v )))
2355+
/// .collect::<HashMap<u32,u32>>()[&0], 30)
2356+
/// ```
2357+
#[cfg(feature = "use_std")]
2358+
fn into_group_map_by<K, V, F>(self, f: F) -> HashMap<K, Vec<V>>
2359+
where
2360+
Self: Iterator<Item=V> + Sized,
2361+
K: Hash + Eq,
2362+
F: Fn(&V) -> K,
2363+
{
2364+
group_map::into_group_map_by(self, f)
2365+
}
2366+
23312367
/// Return the minimum and maximum elements in the iterator.
23322368
///
23332369
/// The return type `MinMaxResult` is an enum of three variants:

0 commit comments

Comments
 (0)