Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of a given string in an ArrayList

Tags:

java

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:

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"

like image 905
lola Avatar asked Oct 07 '11 12:10

lola


1 Answers

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"));
like image 104
JRL Avatar answered Oct 05 '22 14:10

JRL