计算ArrayList中给定字符串的出现次数

时间:2011-10-07 12:13:54

标签: java arraylist

我有一个字符串列表,我浏览它并计算“x”字符串的数量,如下所示,但计数不会打印出预期的值:

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”

5 个答案:

答案 0 :(得分:13)

此处已有existing method

Collections.frequency(collection, object);

在您的情况下,请像这样使用(用此替换所有发布的代码):

System.out.println(java.util.Collections.frequency(table.getValue(), "x"));

答案 1 :(得分:5)

答案 2 :(得分:1)

您需要使用:

list.get(i).equals("x");

!= / ==仅检查参考。

我不知道为什么你要使用ArrayList来计算。你可能会这样:

int count = 0;
for (String s : table.getValue()) {
    if (s.equals("x")) {
        count++;
    }
}
System.out.println( count );

答案 3 :(得分:0)

对于String,您应该使用equals方法。

int ct = 0;
for (String str : table.getValue()) {
    if ("x".equals(str)) { // "x".equals to avoid NullPoniterException
        count++;
    }
}
System.out.println(ct);

答案 4 :(得分:0)

既然你正在寻找元素和大小,我会推荐Guava的Iterables.filter方法

List<String> filtered = Lists.newArrayList(
                     Iterables.filter(myList, 
                                      Predicates.equalTo("x")));
int count = filtered.size();

但正如其他人都指出的那样,代码无效的原因是==