有没有办法计算一个String在ArrayList中出现的次数? 例如,如果数组包含以下字符串:
如何做到以下几点:
是否可以不使用哈希映射?只是为每个循环或if语句使用arraylists,while循环? 任何答案都非常感谢
答案 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);