The number of instances of this row in the array ArrayList

I have a list of lines, I look through it and count the number of lines "x" as shown below, but the count does not display 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 since I have 2 occurrences of "x"

+5
source share
5 answers

There is already an existing method for this :

 Collections.frequency(collection, object); 

In your case, use this: (replace all your code with this):

 System.out.println(java.util.Collections.frequency(table.getValue(), "x")); 
+13
source

You need to use:

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

! = / == checks only the link.

I do not know why you use ArrayList for counting. You are probably something like this:

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

For String, you must use the equals method.

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

Since you are looking for both elements and size, I would recommend the Guava Iterables.filter method

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

But, as everyone else pointed out, the reason your code doesn't work is ==

0
source

All Articles