概要
以前の記事「外部ライブラリを利用せずにGroup ByやGroup By Countを実現したい」では、標準ライブラリのみで頻度集計を行う方法を紹介しました。今回はその補足として、外部クレート itertools を使うことで、頻度集計をより簡潔に記述する方法をご紹介します。
counts() の使い方
itertools::Itertools トレイトには .counts() という便利なメソッドがあり、イテレータの各要素の出現回数を HashMap で返してくれます。
例:文字列中の文字の頻度を数える
use itertools::Itertools;
use std::collections::HashMap;
fn main() {
let text = "abracadabra";
let freq_map: HashMap<_, _> = text.chars().counts();
println!("{:?}", freq_map);
// => {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
}
-
.chars()で文字列を文字に分解 -
.counts()で各文字の出現回数を集計 - 結果は
HashMap<char, usize>型で得られます
環境情報
$ cargo --version
cargo 1.89.0 (c24e10642 2025-06-23)
$ rustc --version
rustc 1.89.0 (29483883e 2025-08-04)
# Cargo.toml
[dependencies]
itertools = "0.14.0"