Reputation: 5789
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"
Upvotes: 5
Views: 19649
Reputation: 77995
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"));
Upvotes: 13
Reputation: 32949
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 ==
Upvotes: 0
Reputation: 420951
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:
Upvotes: 4
Reputation: 4935
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);
Upvotes: 0
Reputation: 9380
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 );
Upvotes: 1