Use TreeMap to count the number of words and output words and bibliographies, with words sorted in ascending order
TreeMap is characterized by a non-repeating element, and the key value of the element can either be sorted by default comparable interface or sorted by comparator comparator, a comparator is designed for TreeMap, this comparator implements comparator interface
//Can be extended to the data from the file or input words from the console to count, only need to join the stream on the lineImport Java.util.map;import Java.util.set;import Java.util.TreeMap; Public classCountWords { Public Static void Main(string[] args) {//TODO auto-generated method stubString text="Hello,good morning. Have a good day! "+"Oh,thank you. Have a good visit! "; Treemap<string,integer> treemap=NewTreemap<string,integer> (); String[] Str=text.split ("[,.! ]"); for(intI=0; i<str.length;i++) {String key=str[i].tolowercase ();if(Key.length () >0){if(!treemap.containskey (key)) {Treemap.put (Key,1);//If there is no map, put it in}Else{int value=treemap.Get(key). Intvalue ();value++; Treemap.put (Key,value);//If you have this word, value plus 1}}} set<map.entry<string, integer>>Set=treemap.entryset ();//Returns the entry rule set in TreeMap for(Map.entry<string, integer> e:Set) {System. out. println (E.getkey () +"\ T"+e.getvalue ()); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java treemap Statistics Number of words