Java – How to count the occurrence of each character in char array

arrayscharjava

I'm trying to count the occurrence of each character in an char array. How many times a specific lower case or upper case letter appears? What would be an effective method as I keep running in circles and into errors?

This is the code I used to populate the array with random characters:

char[] chararray = new char[1000]; 
   for (int i = 0; i < chararray.length; i++) { 
       char c = randomCharacter();
       chararray[i] = c;  
   }//end for  

I've tried creating a second array to count it for both upper and lower case such as, but I'm not sure what to do with it:

int[] counter = new int[52];

Any sort of help would be appreciated it. Thank you.

Best Answer

Here is a relatively straightforward method using Java 8 streams

Character[] charArray = new Character[1000];
IntStream.rand(0, charArray.length)
    .forEach(n -> charArray[n] = randomCharacter());
Map<Character, Long> charCountMap = Arrays.stream(charArray)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());

This leaves you with a map from each character to the number of times it occurs in the array.

Forget efficiency unless you are processing billions of characters a second or you are trying to run it on a digital watch from the 90s.