统计字符串中数字出现的次数,然后按照降序排列,出现次数相同按照键的大小降序排列

package shu.quan.demo;

import java.util.*;

public class demo {
    public static void main(String[] args){
        TreeMap map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        String ss = "134657983254987543279832481643649757858884";
        String[] arr = ss.split("");
        for(int i = 0; i < arr.length; i++){
            int temp = Integer.parseInt(arr[i]);
            if(map.containsKey(temp)){
                map.put(temp,map.get(temp) + 1);
            }else{
                map.put(temp,1);
            }
        }

        //构建数组存储键值,然后进行排序
        int[] arrKey = new int[map.size()];
        int[] arrValue = new int[map.size()];
        int k1 = -1, k2 = -1;
        Set> set = map.entrySet();
        Iterator it =  set.iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            System.out.println(entry.getKey()+":  "+entry.getValue());
            arrKey[++k1] = entry.getKey();
            arrValue[++k2] = entry.getValue();
        }
        //对arrValue进行从大到小的排序,使用选择排序
        for(int i = 0; i < arrValue.length - 1; i++){
            int tempmax = arrValue[i];
            int index = i;
            for(int j = i+1; j < arrValue.length; j++){
                if(tempmax < arrValue[j]){
                        tempmax = arrValue[j];
                        index= j;
                }
            }
            //选出第一个最大值,依次交换位置
            int temp = arrValue[i];
            int temp1 = arrKey[i];
            arrValue[i] = arrValue[index];
            arrKey[i] = arrKey[index];
            arrValue[index] = temp;
            arrKey[index] = temp1;

        }
        for(int i = 0; i < arrValue.length; i++){
            System.out.print("  "+arrKey[i]+":"+arrValue[i]+";");
        }

    }
}

 

你可能感兴趣的:(基础编程)