Skip to content

Commit 4d317f7

Browse files
bors[bot]mmirate
andauthored
Merge #515
515: Add Itertools.counts_by. r=jswrenn a=mmirate This is a fairly straightforward extension of the existing "counts" method. Co-authored-by: Milo Mirate <[email protected]> Co-authored-by: Milo Mirate <[email protected]>
2 parents cc46647 + e096095 commit 4d317f7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/lib.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3083,6 +3083,48 @@ pub trait Itertools : Iterator {
30833083
self.for_each(|item| *counts.entry(item).or_default() += 1);
30843084
counts
30853085
}
3086+
3087+
/// Collect the items in this iterator and return a `HashMap` which
3088+
/// contains each item that appears in the iterator and the number
3089+
/// of times it appears,
3090+
/// determining identity using a keying function.
3091+
///
3092+
/// ```
3093+
/// # use itertools::Itertools;
3094+
/// struct Character {
3095+
/// first_name: &'static str,
3096+
/// last_name: &'static str,
3097+
/// }
3098+
///
3099+
/// let characters =
3100+
/// vec![
3101+
/// Character { first_name: "Amy", last_name: "Pond" },
3102+
/// Character { first_name: "Amy", last_name: "Wong" },
3103+
/// Character { first_name: "Amy", last_name: "Santiago" },
3104+
/// Character { first_name: "James", last_name: "Bond" },
3105+
/// Character { first_name: "James", last_name: "Sullivan" },
3106+
/// Character { first_name: "James", last_name: "Norington" },
3107+
/// Character { first_name: "James", last_name: "Kirk" },
3108+
/// ];
3109+
///
3110+
/// let first_name_frequency =
3111+
/// characters
3112+
/// .into_iter()
3113+
/// .counts_by(|c| c.first_name);
3114+
///
3115+
/// assert_eq!(first_name_frequency["Amy"], 3);
3116+
/// assert_eq!(first_name_frequency["James"], 4);
3117+
/// assert_eq!(first_name_frequency.contains_key("Asha"), false);
3118+
/// ```
3119+
#[cfg(feature = "use_std")]
3120+
fn counts_by<K, F>(self, f: F) -> HashMap<K, usize>
3121+
where
3122+
Self: Sized,
3123+
K: Eq + Hash,
3124+
F: FnMut(Self::Item) -> K,
3125+
{
3126+
self.map(f).counts()
3127+
}
30863128
}
30873129

30883130
impl<T: ?Sized> Itertools for T where T: Iterator { }

0 commit comments

Comments
 (0)