Java sorts the number of occurrences of characters in a string

Source: Internet
Author: User
Tags character set sort sorts

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
Import Java.util.List;
Import Java.util.Map;
/**
* continues to sort the number of occurrences of characters in the character set.
*
* @author Zhaoqing
*/
public class T {
public static void Main (String args[]) {
String str = 12 345678HFDJKSLAHFKJ932189OIEFSJKAR94WERFDSF ";
Map<character, keyvalue> Map = new Hashmap<character, keyvalue> ();
Char C;
KeyValue kv = null;    
for (int i = 0; i < str.length (); i++) {
c = str.charat (i);
KV = Map.get (c);     
if (kv = = null) {
KV = new KeyValue ();
kv.ch = C;
Kv.count = 1;
Map.put (c, KV);    
} else {
kv.count++;
  
}
List<keyvalue> List = new arraylist<keyvalue> (Map.values ());
Collections.sort (list);   
for (KeyValue o:list) {
System.out.println (o.ch + "=" + O.count);

}
}
class KeyValue implements comparable {
public int compareTo (Object obj) {
if (obj instanceof keyvalue) {
KeyValue kv = (keyvalue) obj;
return kv.count-this.count;  
}
Return-1;
}
Char ch;
int count;
}

Run results

f=5
j=3
k=3
s=3
9=3
d=2
e=2
a=2
h=2
3=2
2=2
1=2
r=2
4=2
8=2
o=1
l=1
i=1
w=1
7=1
6=1
5=1

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.