Using Java implementation to find the most occurrences of the characters in the input string and the number of times;

Source: Internet
Author: User

Through the map class implementation, by means of key-value pairs, each character of the input string can be entered as a key, and the number of occurrences of each character as a value is as follows:

public class Find {
public static void Main (string[] args) {
String Scan=new Scanner (system.in). nextline ();//Gets the string entered on the keyboard;
map<character,integer> map = new hashmap<character,integer> ();//Create a new HashMap object;
    

With a For loop, the string's key value is stored in the map

for (int i=0;i<scan.length (); i++) {
Char temp=scan.charat (i);//through loops, each character of the string is found to coexist into temp;
if (map . ContainsKey (temp)) {//If the map has temp this character
Map.put (temp, map.get (temp) +1);//add 1 to the temp value;
}else{//if there is no te in map MP this character,
Map.put (temp, 1);//Set the value of temp to 1;
}
}

/*collection c = map.entryset ();
Iterator it = C.iterator ();
Map.entry<character, integer> Entry;
while (It.hasnext ()) {
Entry = (Map.entry<character, integer>) It.next ();
}
*/
int maxnum = Collections.max (Map.values ());//Call the Max method of the collections class, get a collection of the values of the map, and find out the maximum value;
Set<chara cter> set = new hashset<character> ();//Create a Set object
for (Map.entry<character, integer> entry1:        Map.entryset ()) {//through the loop of the collection, place the value of the map into the entry1, and find the key of the Maxnum with the largest value by Entry1;
        if (Entry1.getvalue () ==maxnum) {
Set.add (Entry1.getkey ());
}
}

System.out.println ("The most occurrences of the letter is:" +set+ "the maximum number of occurrences is" +maxnum);

}

}

The

uses the Java implementation to find the most occurrences of the characters in the input string and the number of occurrences;

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.