Java treemap Statistics Number of words

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.