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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7687062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:59:36  来源:igfitidea点击:

Count occurrences of a given string in an ArrayList

javaarraylist

提问by lola

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”

回答by JRL

There already is an existing methodfor 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"));

回答by aioobe

You should compare strings using equalsinstead of ==. I.e. change

您应该使用equals而不是比较字符串==。即改变

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

to

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

==compares references, while .equalscompares actual content of strings.

==比较引用,而.equals比较字符串的实际内容。



Related questions:

相关问题:

回答by MasterCassim

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. You would probably something like that:

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

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

回答by Vaandu

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

回答by John B

Since you are looking for both the elements as well as the size, I would recommend Guava's Iterables.filtermethod

由于您正在寻找元素和大小,我会推荐番石榴的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 ==

但正如其他人所指出的,您的代码无法正常工作的原因是 ==