How to count how many times an item repeats in an Array with unknown size?

Asked

Viewed 4,918 times

3

How to count how many times an item appears in an Array I don’t know the size of? The array was created from a . CSV.

  • Considered using a loop for(Object object : csv) instead of something for(int i = 0; i < csv.length; i++)?

  • 1

    If you have an array then you can get its size - just access the property length array - independent of how the array was created.

  • @user2296455 if the answer has solved your question let us know, if you do not also warn. :)

2 answers

6

I think you can do so, create a method and pass by parameter the Array and the Item to be checked, if it is 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, no IDE here to test.

5

The code below serves for any type 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;
}
  • Very good, didn’t know that! But even if it passes a normal array will work?

  • @Joãoneto The way it is you can not pass a normal array, but this special "for" also works with arrays, so just change the signature of the method without modifying the content.

  • Got it @utluiz. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.