对Map中的Value进行降序排序,当Value相同时,按照Key降序排序

package com.ethjava;
import java.util.*;
public class mappaixu1 {
    public static void main(String[] args){

        Map<Integer,Integer> hashMap=new HashMap<Integer, Integer>();
        hashMap.put(1,10);
        hashMap.put(5,7);
        hashMap.put(2,9);
        hashMap.put(3,7);
        hashMap.put(3,6);//key是不可重复的,当这里再次输入Key=3时的,将会覆盖掉前面的(3,7)
        hashMap.put(4,7);

        //遍历
        for(Map.Entry<Integer,Integer> e:hashMap.entrySet()){
            System.out.println("Key: "+e.getKey()+"对应的Value: "+e.getValue());
        }
        //Key: 1对应的Value: 10
        //Key: 2对应的Value: 9
        //Key: 3对应的Value: 6
        //Key: 4对应的Value: 7
        //Key: 5对应的Value: 7
        //这里为什么自动按照key升序排序输出???为什么
        // 某梦说,这里是因为凑巧正序输出,hashMap输出相对于输入是无序的。

        //下面按照Value进行倒序排列
        ArrayList<Map.Entry<Integer,Integer>> arrayList=new ArrayList<Map.Entry<Integer, Integer>>(hashMap.entrySet());

        Collections.sort(arrayList,new Comparator<Map.Entry<Integer,Integer>>(){
            @Override

            public int compare(Map.Entry<Integer,Integer> o1,Map.Entry<Integer,Integer> o2 ){
                //按照Value进行倒序,若Value相同,按照Key正序排序
                //方法1:return o2.getValue() - o1.getValue();
                //方法2:return o2.getValue().compareTo(o1.getValue());//对于Integer,String都是可以应用的
                //按照Value进行倒序,若Value相同,按照Key倒序排序
                int result = o2.getValue().compareTo(o1.getValue());
                //方法学习:public int compareTo( NumberSubClass referenceName )
                //referenceName -- 可以是一个 Byte, Double, Integer, Float, Long 或 Short 类型的参数。
                //返回值:如果指定的数与参数相等返回0。
                // 如果指定的数小于参数返回 -1。
                //如果指定的数大于参数返回 1
                if(result!=0){
                    return result;//即两个Value不相同,就按照Value倒序输出
                }else{
                    return o2.getKey().compareTo(o1.getKey());}
                    //若两个Value相同,就按照Key倒序输出
            }
        });
        //这里arrayList里的顺序已经按照自己的排序进行了调整
        for(int i=0;i<arrayList.size();i++){
            System.out.println(arrayList.get(i));
            //方法一和方法二输出:
            //1=10
            //2=9
            //4=7
            //5=7
            //3=6
            //当按照Value倒序排序,但是当Value相同时,按照Key顺序正序排序

            //方法二
            //1=10
            //2=9
            //5=7
            //4=7
            //3=6
            //当按照Value倒序输出,但是当Value相同时,按照Key倒序输出
        }

        for(Map.Entry<Integer,Integer> e:hashMap.entrySet()){

            System.out.println(e);
            //1=10
            //2=9
            //3=6
            //4=7
            //5=7
            //这里表明hashMap中存取的内容顺序并没有进行任何改变,改变的是arrayList里的内容的顺序
        }






    }
}

参考:

https://blog.csdn.net/LvJinYang/article/details/102875095

https://blog.csdn.net/u014388729/article/details/80156645

发布了45 篇原创文章 · 获赞 8 · 访问量 5868

猜你喜欢

转载自blog.csdn.net/wenyunick/article/details/103336828