Assume we're asked to count and print the occurrences of each character in a given String. For simplicity, the string has just lowercase letters. I wrote these 2 functions and I want to know which one is more efficient/preferable in Java.
Function 1:
private void countAndPrintArray1(String str){
int[] a = new int[26];
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int index = c - 'a';
a[index] = a[index] + 1;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = a[c -'a'];
System.out.println(c+" -> "+ freq);
}
}
Function 2:
private void countAndPrintArray2(String str){
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.getOrDefault(c, 0) + 1;
map.put(c, freq);
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int freq = map.get(c);
System.out.println(c+" -> "+ freq);
}
}