JAVA给定字符串数组返回数组各值(Map按照Key排序)

public static Map<String, Integer>publicMap = new LinkedHashMap<String,Integer>();

    publicstatic void main(String[] args) {
       String str = "b|c|d|e|f|a|b|c|d|e|a|a";//从数据库循环累加标签

       String[] ss = str.split("\\|");
       System.out.println(getTopMap(ss, 10).toString());
    }

   
    privatestatic Map<String, Integer>getTopMap(String[] strs, int topCount) {
       Map<String, Integer> map = newLinkedHashMap<String,Integer>();
       for (String s : strs){              //存到Map中 key:名字 value:次数
           if (publicMap.containsKey(s)) {  //包含则 value+1
               publicMap.put(s, publicMap.get(s) + 1);
           } else {
               publicMap.put(s, 1);
           }
       }

       String setStr = publicMap.keySet().toString();
       String[] keys = setStr.substring(1,setStr.lastIndexOf("]")).split(",");

       sortKeyByValues(keys);//按照value对key进行最值排序

       int count = topCount > keys.length ? keys.length :topCount;

       for (int i = 0; i < count; i++) {
           map.put(keys[i].trim(), publicMap.get(keys[i].trim()));
       }
       return map;
    }
   //按照value对key进行最值排序

    privatestatic void sortKeyByValues(String[] keys) {
       boolean isSwap = true;
       String temp;
       String key1;
       String key2;
       int value1;
       int value2;

       for (int i = 0; i < keys.length&& isSwap; i++) {
           isSwap = false;
           for (int j = 0; j < keys.length - 1; j++) {
               key1 = keys[j + 1].trim();
               key2 = keys[j].trim();
               value1 = Integer.parseInt(publicMap.get(key1).toString());
               value2 = Integer.parseInt(publicMap.get(key2).toString());
               if (value1 > value2) {
                   temp = keys[j].trim();
                   keys[j] = keys[j + 1].trim();
                   keys[j + 1] = temp;
                   isSwap = true;
               }
           }
       }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值