无论如何都要计算重复的字符串

时间:2016-12-11 19:37:17

标签: java for-loop arraylist

有没有办法计算一个String在ArrayList中出现的次数? 例如,如果数组包含以下字符串:

  1. "扑热息痛"
  2. " Nurofen"
  3. " Nurofen"
  4. 如何做到以下几点:

    1. Panadol 1
    2. Nurofen 2
    3. 是否可以不使用哈希映射?只是为每个循环或if语句使用arraylists,while循环? 任何答案都非常感谢

1 个答案:

答案 0 :(得分:0)

您可以使用双循环(+ contains - 检查)来执行此操作,但它无效...

ArrayList<String> words = new ArrayList<>();
words.add("Cat");
words.add("Dog");
words.add("Bird");
words.add("Dog");
words.add("Cat");
words.add("Dog");

ArrayList<String> alreadyParsed = new ArrayList<>();
for (String word : words) {
    if (alreadyParsed.contains(word)) {
        continue;
    }

    int counter = 0;
    for (String candidate : words) {
        if (candidate.equals(word)) {
            counter++;
        }
    }

    System.out.println(word + " " + counter);
    alreadyParsed.add(word);
}

HashMap相同:

ArrayList<String> words = new ArrayList<>();
words.add("Cat");
words.add("Dog");
words.add("Bird");
words.add("Dog");
words.add("Cat");
words.add("Dog");

HashMap<String, Integer> counters = new HashMap<>();
for (String word : words) {
    if (counters.containsKey(word)) {
        counters.put(word, counters.get(word) + 1);
    } else {
        counters.put(word, 1);
    }
}

System.out.print(counters);