算定字符串的出现在一个ArrayList [英] Count occurrences of a given string in an ArrayList

查看:89
本文介绍了算定字符串的出现在一个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"

推荐答案

有已经是<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#frequency%28java.util.Collection,%20java.lang.Object%29\">existing此方法:

Collections.frequency(collection, object);

在你的情况,这样使用(替换所有的贴code本的):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆