Map: gets the number of occurrences of each letter in a string. It is a map string.
1 package cn. itcast. p1.map. test; 2 3 import java. util. iterator; 4 import java. util. map; 5 import java. util. treeMap; 6/* exercise: 7 * print the result: a (1) B (2) c (3 )... 8 * Train of Thought: 9 * analysis of the results shows that there is a ing between letters and times. There are many such relationships. 10 * a lot of wine needs to be stored. containers that can store mappings include arrays and Map sets. 11 * is the link side an ordered number? If there is no 12 *, the Map set is used. It is also found that the uniqueness of one party has a sequence such as a B c... 13 * you can use the TreeMap set. 14*15 * This set should ultimately store the correspondence between letters and times. 16*17*1. Because the operation is performed on letters in the string, the string is first converted into a character array. 18*2. traverse the character array and use each letter as the key to query the Map set table. 19 * If the primary key does not exist, use the letter as the key and 1 as the value to store 20 in the map set. * If the primary key exists, the corresponding value of the primary key is extracted and added to 1, store the letter and the value after + 1 to the map set with the same 21 * key, and the value will overwrite. In this way, the number of times of the letter is recorded 22*23*3. The traversal ends. The map set records the occurrences of all letters. 24*25 */26 27 public class Maptest {28 29 public static void main (String [] args) {30 String str = "fdgavAde bs5dDadfgjkdgasxbccxvvcxn1bnb-dfs "; 31 32 String s = getCharCount (str); 33 34 System. out. println (s); 35 36} 37 38 private static String getCharCount (String str) {39 // convert the String to a character array 40 char [] chs = str. toCharArray (); 41 // define map set Table 42 Map <Character, Integer> map = new TreeMap <Character, Integer> (); 43 4 4 for (int I = 0; I <chs. length; I ++) 45 {46 // if (! (Chs [I]> = 'A' & chs [I] <= 'Z' | chs [I]> = 'A' & chs [I] <= 'Z ')) 47 if (! (Character. toLowerCase (chs [I])> = 'A' & Character. toLowerCase (chs [I]) <= 'Z') 48 continue; 49 50 // use the letters in the array as the key to query the map table. 51 Integer value = map. get (chs [I]); 52 53 int count = 1; 54 55 if (value! = Null) 56 {57 count = value + 1; 58} 59 6061 62 map. put (chs [I], count); 63} 64 65 return mapToString (map); 66} 67 68 private static String mapToString (Map <Character, Integer> map) {69 StringBuilder sb = new StringBuilder (); 70 71 Iterator <Character> it = map. keySet (). iterator (); 72 73 while (it. hasNext () 74 {75 Character key = it. next (); 76 Integer value = map. get (key); 77 sb. append (key + "(" + value + ")" + ""); 78} 79 80 return sb. toString (); 81 82} 83 84}