5

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

this gives [] it should be 2 as I have 2 occurrences of "x"

aioobe
  • 413,195
  • 112
  • 811
  • 826
lola
  • 5,649
  • 11
  • 49
  • 61

5 Answers5

13

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"));
JRL
  • 76,767
  • 18
  • 98
  • 146
4

You should compare strings using equals instead of ==. I.e. change

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

to

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

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


Related questions:

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • ok, I 've changed to equals, the problem now is that print me [1,2] instead of[2] ? – lola Oct 07 '11 at 12:32
  • That's because you *add* `count` to the list each time you increment it. Either just print `count` instead of `list`, or remove the previous `count` from `list` before you add it again. – aioobe Oct 07 '11 at 12:34
1

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:

int count = 0;
for (String s : table.getValue()) {
    if (s.equals("x")) {
        count++;
    }
}
System.out.println( count );
Tobias
  • 9,170
  • 3
  • 24
  • 30
0

For String you should use equals method.

int ct = 0;
for (String str : table.getValue()) {
    if ("x".equals(str)) { // "x".equals to avoid NullPoniterException
        count++;
    }
}
System.out.println(ct);
Vaandu
  • 4,857
  • 12
  • 49
  • 75
0

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

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 ==

John B
  • 32,493
  • 6
  • 77
  • 98