/* Exercise: "Kbashbdjsgfwhofihbfkwejhfiubjzfhaads" gets the number of occurrences of the letter in the string. Want to print results: A (3) B (4) d (2) ... The results show that each letter has a corresponding number of times. , indicating that there is a mapping between the characters and the number of times. Note: When a mapping relationship is found, you can select the Map collection. Because the map collection stores the mapping relationship. Why use a map collection? When there is a mapping between the data, you think of the map collection. Idea: 1, use the Charat () method of the string class to iterate through each character in a string. 2, define a map, because the output is ordered, so use the TreeMap collection. 3, iterate through each character in the string, determine if there is a key in the map, if present, the key value +1, if not present, the character as a key to map, and give the key value of 1.*/import Java.util.*;class MapTest3 { public static void Main (string[] args) {String str= "kbashbdjsgfwhofihbfkwejhfiubjzfhaads"; TreeMap tm=new TreeMap (); for (int i=0;i<str.length (); i++) {char ch=str.charat (i); Tm.containskey (CH))) Tm.put (ch,1); else{int t= (int) (Tm.get (CH)) +1;tm.put (ch,t);}} Set S=tm.keyset (); Iterator it=s.iterator (); while (It.hasnext ()) {char chr= (char) it.next (); int num= (int) tm.get (CHR); SOP (chr+ "..." +num);}} public static void Sop (Object obj) {System.out.println (obj);}}
Java map Exercise-Get the number of occurrences of letters in a string (TreeMap implementation)