@@ -3083,6 +3083,48 @@ pub trait Itertools : Iterator {
3083
3083
self . for_each ( |item| * counts. entry ( item) . or_default ( ) += 1 ) ;
3084
3084
counts
3085
3085
}
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
+ }
3086
3128
}
3087
3129
3088
3130
impl < T : ?Sized > Itertools for T where T : Iterator { }
0 commit comments