计算给定字符串在 ArrayList 中的出现次数 [英] Count occurrences of a given string in an ArrayList
本文介绍了计算给定字符串在 ArrayList 中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串列表,我浏览它并计算x"字符串的数量,如下所示,但计数没有打印出预期值:
I have a list of strings , I browse it and count number of "x" strings as below but the count doesn't print me the expected value:
ArrayList<Integer> list = new ArrayList<Integer>();
List<String> strings = table.getValue(); //this gives ["y","z","d","x","x","d"]
int count = 0;
for (int i = 0; i < strings.size(); i++) {
if ((strings.get(i) == "x")) {
count++;
list.add(count);
}
}
System.out.println(list);
这给 []
它应该是 2,因为我有 2 次出现x"
this gives []
it should be 2 as I have 2 occurrences of "x"
推荐答案
已经有一个 现有方法:
Collections.frequency(collection, object);
在你的情况下,像这样使用(用这个替换你发布的所有代码):
In your case, use like this (replace all of your posted code with this):
System.out.println(java.util.Collections.frequency(table.getValue(), "x"));
这篇关于计算给定字符串在 ArrayList 中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文