Packagecn.itcast.p1.map.test;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.TreeMap; Public classTestMap {/*** Exercise: * "FDGAVCBSACDFS+++AA&&BBB" gets the number of occurrences of each letter in the string. * Required printing results are: A (2) B (1) ...; * Idea: * The analysis of the results shows that there is a mapping between the letters and the number of times. And it's a lot of relationships. * Many require storage, and the containers that can store the mappings have arrays and map collections. * Relationship One way ordinal number? No! * That's using the Map collection. Also found to be able to ensure that the uniqueness of the party has a sequence such as a b c ... * so you can use the TreeMap collection. * 1. Because the action is the letter in the string, so the string into a character array * 2. Iterates through the character array, and if the letter does not exist, the value of the key corresponding to the letter is 1 stored in the map * If the letter exists, the value of the key corresponding to the letter of +1 is stored in the map, The same key will be overwritten, * This will record the number of occurrences of each letter in the string * 3. Traverse end Map records the number of occurrences of all letters*/ Public Static voidMain (string[] args) {String str= "Asbbbadccfdssf+df-dfucccier%aa+hfffhdas"; String s=Gettreecount (str); System.out.println (s); } Public Staticstring Gettreecount (String str) {//to turn a string into a character array Char[] ch =Str.tochararray (); //defines a mapping relationship that TREEMAP uses to store letters and timesMap<character, Integer>map =NewTreemap<character, integer>(); for(inti = 0; i < ch.length; i++) { if(! (Ch[i] >= ' A ' && ch[i] <= ' z ' | | ch[i] >= ' A ' && ch[i]<= ' z ')){ Continue; } //use the letters in the character array as keys to check the map tableInteger value =Map.get (Ch[i]); intCount = 1; if(Value! =NULL) {Count= value + 1; } map.put (Ch[i], count); /*if (value = = null) {Map.put (ch[i], 1); }else{Map.put (Ch[i], value+1); }*/ } returnmaptostring (map); } Private StaticString maptostring (Map<character, integer>map) {StringBuilder SB=NewStringBuilder (); /*iterator<map.entry<character, integer>>it = Map.entryset (). Iterator (); while (It.hasnext ()) {map.entry<character, integer> mapentry = It.next (); Character key = Mapentry.getkey (); Integer value = Mapentry.getvalue (); Sb.append (key+ "(" +value+ ")"); }*/Iterator<character>it =Map.keyset (). iterator (); while(It.hasnext ()) {Character key=It.next (); SYSTEM.OUT.PRINTLN (key); Integer value=Map.get (key); Sb.append (Key+ "(" +value+ ")"); } returnsb.tostring (); }}
Java Collection TreeMap Application---to find the number of occurrences of each letter in a string