Map集合排序

//map排序

public static voidmain(String[] args) {
       Map map = new HashMap();
       map.put("a", 1);
       map.put("c", 3);
        map.put("e",5);
       map.put("d", 4);
       map.put("b", 2);
        
       System.out.println("排序前===="+map);
        
        //使用mpa.entry对map进行排序
        Setset = map.entrySet();
       Map.Entry[] entry = (Entry[]) set.toArray(new Map.Entry[set.size()]);
       Arrays.sort(entry, new Comparator() { 
           public int compare(Object arg0, Object arg1) { 
                Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString()); 
                Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString()); 
                return key1.compareTo(key2); 
            } 
        });
        //排序后
       System.out.print("排序后===");
        for(int i=0;i            System.out.print(entry[i]+" ");
        }
       System.out.print("\n");
        
        //获取enrty对象里对应的键或值
       Map lastMap = new HashMap();
       lastMap.put("a", "定力");
       lastMap.put("b", "耐力");
       lastMap.put("c", "活力");
        lastMap.put("d","脑力");
       lastMap.put("e", "动力");
        int t= 1;
       String str = ""; //性格描述
        for(int i=0;i

           if (entry.length - i <= 3) {

               System.out.println(entry[i].getKey()+"==="+entry[i].getValue());

               str = str+" "+lastMap.get(entry[i].getKey());
               t += 1;
           } else {
               System.out.println(entry[i]);
           }
        }
       System.out.println("获取到的值===="+str);
    }

 

你可能感兴趣的:(Java常用代码)