How to count how many times an item is repeated in an Array of unknown size?

2

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.

    
asked by anonymous 11.11.2014 / 00:45

2 answers

6

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.

    
11.11.2014 / 04:25
4

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;
}
    
11.11.2014 / 10:40