如何计算存储在数组列表中的每个句子中每个单词的出现次数?

How do I count the occurrences of each word in each of sentences stored in arraylists?

我有一个 arraylist 来保存文档的每一行,例如-

list.add("I like to play pool")

list.add("How far can you run")

list.add("Do you like fanta because I like fanta")

我想遍历存储在 arrayList 中的每个句子,并计算每个句子中每个单词的出现次数,有人可以帮我吗?

编辑 这是我尝试过的,但它只告诉我每个句子的出现。我需要它能够计算每个句子的单词数。

Set<String> unique = new HashSet<String>(list);
        for (String key : unique) {
            System.out.println(key + ": " + Collections.frequency(list, key));
  1. 让我们打电话给你的ArrayList<String> list
  2. 让我们创建一个 String[] 的列表 list2 3、Split Sentences到数组中。
  3. 出现次数

代码:

ArrayList<String> list = new ArrayList<>();
//add sentences here
list.add("My first sentence sentence");
list.add("My second sentence1 sentence1");

ArrayList<String[]> list2 = new ArrayList<>();
for (String s : list) { list2.add(s.split(" "));};
for (String[] s : list2) {
    Map<String, Integer> wordCounts = new HashMap<String, Integer>();

    for (String word : s) {
        Integer count = wordCounts.get(word);
        if (count == null) {
            count = 0;
        }
        wordCounts.put(word, count + 1);
    }
    for (String key : wordCounts.keySet()) {
        System.out.println(key + ": " + wordCounts.get(key).toString());
}