how to know the most repeated char within an array?

0

I need to know the most repeated char within an array

Scanner var = new Scanner(System.in);
String cad;
System.out.println("escribe caracteres");
cad = var.nextLine();
char[] a = cad.toCharArray();

I do not stop there.

    
asked by Fernando Antonio González 21.04.2018 в 21:07
source

1 answer

0

It occurs to me that you use a Map where you can store the number of times that the same character appears in the chain. You must take into account that, for example, A != de a , like a != á .

    Map<Character, Integer> charCounts = new HashMap<>();
    int maxCount = -1;
    Character maxChar = null;
    for (char item : a) {// a es tu arreglo de char
        Integer count = charCounts.get(item);
        if (count == null) {
            count = 0;
        }

        charCounts.put(item, ++count);

        if (count > maxCount) {
            maxCount = count;
            maxChar = item;
        }
    }

Then in the variable maxChar you will have the first character that is repeated in the chain. For example, in the chain "coconut" the first character that repeats most is ña 'c'.

Note that the variables maxCount and maxChar I use to avoid having to travel the map after having counted all the characters.

    
answered by 21.04.2018 / 23:44
source