简体   繁体   English

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

[英]Count occurrences of a given string in an ArrayList

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: 我有一个字符串列表,我浏览它并按如下所示计算“ 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);

this gives [] it should be 2 as I have 2 occurrences of "x" 这给[]应该是2,因为我有2次出现“ x”

There already is an existing method for this: 已经存在用于此目的的方法

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"));

You should compare strings using equals instead of == . 您应该使用equals而不是==来比较字符串。 Ie change 即改变

if ((list.get(i) == "x"))
                 ^^

to

if ((list.get(i).equals("x")))
                 ^^^^^^

== compares references, while .equals compares actual content of strings. ==比较引用,而.equals比较字符串的实际内容。


Related questions: 相关问题:

You need to use: 您需要使用:

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

!= / == only checks the reference. != / ==仅检查引用。

I don't knwo why you're using a ArrayList to count. 我不知道为什么要使用ArrayList进行计数。 You would probably something like that: 您可能会这样:

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

For String you should use equals method. 对于String,应使用equals方法。

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

Since you are looking for both the elements as well as the size, I would recommend Guava's Iterables.filter method 由于您同时在寻找元素和大小,因此我建议使用Guava的Iterables.filter方法

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

But as everyone else has pointed out, the reason your code is not working is the == 但正如其他人指出的那样,您的代码无法正常工作的原因是==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM