Count the number of occurrences of a word

Source: Internet
Author: User
Tags stringbuffer
public class Findmaxword {
Count the number of occurrences of a word
public static string Statlist (String str) {
StringBuffer sb = new StringBuffer ();
Hashmap<string, integer> has = new hashmap<string, integer> (); Open a hash table
string[] Slist = Str.split ("\\s");
for (int i = 0; i < slist.length; i++) {
if (!has.containskey (Slist[i])) {//If there is no such word
Has.put (Slist[i], 1);
} else {//if any, add 1 to the number of times
Has.put (Slist[i], Has.get (Slist[i]) + 1);
}
}
Traverse Map
Iterator Iterator = Has.keyset (). Iterator ();
int max=0;
String Maxword = "";
while (Iterator.hasnext ()) {
String word = (string) iterator.next ();

if (Has.get (word). Intvalue () > Max) {
max = Has.get (word);
Maxword = Word;
}

}
return Maxword;
}


public static void Main (string[] args) {
string s = new String (
"Hello Hell hello You");
System.out.println (Statlist (s));
}
}

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.