本帖最后由 李天甲 于 2012-6-20 13:55 编辑
- import java.util.*;
- /*统计字符串中字符出现的次数,通过比较方法打印出了按取出字符次数的排序,
- * 但是怎么把这个排序方法传入StringBuffer容器中,让它能按照这个方法打印出来呢??
- * 通过value的比较后怎么放进容器中把比较后的方法打印出呢?
- * 现在这个打印结果是没调用排序方法的默认的字符排序。*/
- class xp {
- public static void main(String[] args) {
- String s = charCount("abadcdffbaeba");
- System.out.println(s);
- }
- public static String charCount(String str) {
- char[] chs = str.toCharArray();//将字符串转成字符数组
- TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
- int count = 0;
- for (int x = 0; x < chs.length; x++) {
- Integer value = tm.get(chs[x]);
- if (value != null)
- count = value;
- count++;
- tm.put(chs[x], count); //放进容器了
- count = 0;
- }
- System.out.println(tm); //打印出来了
- List<?> list = new ArrayList<Object>(tm.entrySet()); //list放入索引
- Collections.sort(list, new Comparator<Object>() {
- public int compare(Object o1, Object o2) {
- Map.Entry obj1 = (Map.Entry) o1;
- Map.Entry obj2 = (Map.Entry) o2;
- //System.out.println("这是在干啥"+obj1);
- return ((Integer) obj1.getValue()).compareTo((Integer) obj2
- .getValue());
- }
- });
- StringBuffer sb = new StringBuffer();
- for(int x=0;x<list.size();x++){
- Map.Entry me=(Map.Entry)list.get(x);
- Character ch = (Character) me.getKey();
- Integer value = (Integer) me.getValue();
- sb.append(ch + "(" + value + ")");
- }
- return sb.toString();
-
- /*StringBuffer sb = new StringBuffer();
- Set<Map.Entry<Character, Integer>> entry = tm.entrySet();
- Iterator<Map.Entry<Character, Integer>> it = entry.iterator();
- while (it.hasNext()) {
- Map.Entry<Character, Integer> me = it.next();
- Character ch = me.getKey();
- Integer value = me.getValue();
- sb.append(ch + "(" + value + ")");
- }
- return sb.toString();*/
- }
- }
复制代码 呵呵,你的意思是这样么?我照猫画虎打了一个
请参见代码
呵呵,写成size-1了,笔误哈
|