I have a class written that takes a string, counts the occurrences of each letter within the string and then prints the occurrences of each. I want this to be displayed alphabetically, but not sure how to do this.
import java.util.ArrayList; // import the ArrayList class class CryptCmd { public static void CryptCmd(String str) { ArrayList<String> occurs = new ArrayList<>(); final int MAX_CHAR = 256; // Create an array of size 256 i.e. ASCII_SIZE int[] count = new int[MAX_CHAR]; int len = str.length(); // Initialize count array index for (int i = 0; i < len; i++) count[str.charAt(i)]++; // Create an array of given String size char[] ch = new char[str.length()]; for (int i = 0; i < len; i++) { ch[i] = str.charAt(i); int find = 0; for (int j = 0; j <= i; j++) { // If any matches found if (str.charAt(i) == ch[j]) find++; } if (find == 1) occurs.add("Number of Occurrence of " + str.charAt(i) + " is: " + count[str.charAt(i)] + "n"); } System.out.println(String.join("",occurs)); int total = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) != ' ') total++; } System.out.println("Total chars is " + total); } }
So far the print displays in the order the letter was found, i.e
"Hello" = Number of Occurrence of H is: 1 Number of Occurrence of e is: 1 Number of Occurrence of l is: 2 Number of Occurrence of o is: 1 Total chars is 5
The desired output is this, ordered alphabetically i.e
"Hello" = Number of Occurrence of e is: 1 Number of Occurrence of H is: 1 Number of Occurrence of l is: 2 Number of Occurrence of o is: 1 Total chars is 5
Advertisement
Answer
Before printing just add below sorting logic
Collections.sort(occurs, (a,b) -> a.compareToIgnoreCase(b));