计算 ArrayList 中单词的出现次数 [英] Count occurrences of words in ArrayList

查看:29
本文介绍了计算 ArrayList 中单词的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList 包含重复条目的单词.

I have an ArrayList of words with duplicate entries.

我想计算并保存数据结构中每个单词的出现次数.

I want to count and save occurrences for each word in a data structure.

我该怎么做?

推荐答案

如果你没有大量的字符串,实现它的最短方法是使用 Collections.frequency 方法,比如这个:

If you don't have a huge list of strings the shortest way to implement it is by using Collections.frequency method, like this:

List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("aaa");

Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
    System.out.println(key + ": " + Collections.frequency(list, key));
}

输出:

aaa: 2
bbb: 1

这篇关于计算 ArrayList 中单词的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆