记录:根据value对Map进行排序

public class t1 {

    public static void main(String[] args) {
        String[] A = {"i am a coder", "Coder Coder", "Code"};  // 统计coder的个数并且 根据含有个数的字符串排序
        int n = A.length;

        // 找出来并且排序
        Map<Integer, Integer> map = new TreeMap<>();
        int count = 0;
        int res;
        int idx = 0;
        for (String s : A){
            res = 0;
            String[] s1 = s.split(" ");
            for (String s2 : s1){
                // 统计一个字符串里面有多少个coder
                if (s2.toLowerCase().equals("coder")) res++;
            }
            if (res == 0) idx++;
            map.put(count++, res);
//           map.put(res, count++);
        }
        Map<Integer, Integer> newMap = sortMap(map);

        String[] outputArr= new String[n - idx];
        count = 0;
        for (int i : newMap.keySet()){
            int val = newMap.get(i);
            if (val == 0) continue;;
            
            outputArr[count++] = A[i];
        }
    
        System.out.println(newMap);  // outputArr也是最终的结果


    }

    public static Map<Integer, Integer> sortMap(Map<Integer, Integer> map){
        Map<Integer, Integer> sortedMap = new LinkedHashMap<>();

        ArrayList<Map.Entry<Integer, Integer>> entryArrayList = new ArrayList<>(map.entrySet());

        Collections.sort(entryArrayList, new MyNewComparator2());
        Iterator<Map.Entry<Integer, Integer>> iter = entryArrayList.iterator();
        Map.Entry<Integer, Integer> tmpEntry = null;
        while (iter.hasNext()){
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }
}

class MyNewComparator2 implements Comparator<Map.Entry<Integer, Integer>> { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
        return o2.getValue() - o1.getValue();
    }
}



记录
#笔经#
全部评论

相关推荐

少糖去冰的小师弟很沉稳:一群cs公司lz摇奶茶都不止这点钱,md3k***
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务