- public class statString {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str="abadcdffbaeba";
- System.out.println(CharCount(str));
- }
-
- public static String CharCount(String str)
- {
- char[] ch=str.toCharArray();
-
- TreeMap<Character, Integer> map=new TreeMap<Character, Integer>();
-
- for (int i = 0; i < ch.length; i++)
- {
- Integer value=map.get(ch[i]);
- if(value==null)
- {
- map.put(ch[i], 1);
- }
- else {
- value=value+1;
- map.put(ch[i], value);
- }
- }
-
- ArrayList<Map.Entry<Character,Integer>> infoidsList=
- new ArrayList<Map.Entry<Character,Integer>>(map.entrySet());
-
- Collections.sort(infoidsList,new myComparator());
- StringBuilder sBuilder=new StringBuilder();
-
- for (int i = 0; i < infoidsList.size(); i++) {
- //System.out.println(infoidsList.get(i).toString());
- sBuilder.append(infoidsList.get(i).getKey()+":"+infoidsList.get(i).getValue().toString()+",");
- }
-
- String result=sBuilder.deleteCharAt(sBuilder.length()-1).toString();
-
- return result;
- }
- }
复制代码- import java.util.Comparator;
- import java.util.Map;
- import java.util.Map.Entry;
- public class myComparator implements Comparator<Map.Entry<Character,Integer>>
- {
- @Override
- public int compare(Entry<Character, Integer> o1,
- Entry<Character, Integer> o2) {
- // TODO Auto-generated method stub
- return o1.getValue()-o2.getValue();
- }
-
- }
复制代码 |