Original: http://www.open-open.com/code/view/1456919325625
ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set;ImportJava.util.TreeMap;/** Count the number of occurrences of each letter in the ABACBACDADBC, the output format is: A (4) B (3) C (3) d (2) * * The reason for selecting TreeMap is: Key is not duplicated and sorted out in order * idea: * 1. Convert string Abacbacdadbc to Character array * 2. Take a character, compare it to the key in TreeMap * 2.1 If there is a corresponding character in the TreeMap, then remove and increment, and then deposit TREEMAP * 2.2 If there is no corresponding character in TreeMap, the character is stored directly, value=1 /c0>*/ Public classA3b1c2_treemaptest { Public Static voidMain (string[] args) {TreeMap<string, integer> tm=NewTreemap<>(); String String= "Abacbacdadbc"; Char[] Ch=String.tochararray (); for(Charr:ch) { //Tm.put (string.valueof (R), 1); //System.out.println (R); if(Comparekey (R, TM)) {intI=Tm.get (string.valueof (R)); I++; Tm.put (string.valueof (R), i); }Else{tm.put (string.valueof (R),1); }} System.out.println (tm); Set<map.entry<string, integer>> entryset=Tm.entryset (); Iterator<map.entry<string, integer>> iterator=Entryset.iterator (); while(Iterator.hasnext ()) {Map.entry<string, integer> me=Iterator.next (); String Key=Me.getkey (); intValue=Me.getvalue (); System.out.print (Key+ "(" +value+ ")"); } } Public Static BooleanComparekey (CharC,treemap<string, integer>TreeMap) { if(Treemap.containskey (string.valueof (c))) {return true; } return false; }}
The number of occurrences of each letter in Java statistics ABACBACDADBC, the output format is: A (4) B (3) C (3) d (2)