How do I count how many times an item appears in an Array that I do not know the size of? The array was created from a .CSV.
How do I count how many times an item appears in an Array that I do not know the size of? The array was created from a .CSV.
I think you can do this by creating a method and passing the Array and Item to be checked as a String Array, for example:
public int contarRepeticoes(String[] array, String valor) {
int contador = 0;
if(array!=null) {
for(int i=0; i<array.length(); i++) {
if(array[i]!=null) {
if(array[i].equals(valor)) {
contador++;
}
}
}
} else {
System.out.println("Vetor nulo");
}
return contador;
}
I think something like this works, so no IDE here to test.
The code below is for any kind of input data (String, int, double etc):
public static int contaArray(ArrayList<Object> array, Object valorProcurado){
int contador = 0;
if (array != null){
for (Object item : array){
if (item != null && item.equals(valorProcurado)){
contador++;
}
}
}
return contador;
}