java中根据value对key进行排序

来源:互联网 发布:琴萝捏脸数据 编辑:程序博客网 时间:2024/05/21 17:10
public ArrayList<String> getAppSort(){       
        this.getAppDataFromDB();        
        maps = this.sortByValue(maps,isOrder);        
        Iterator it = maps.entrySet().iterator();
        while (it.hasNext()) {


            Map.Entry pairs = (Map.Entry) it.next();
            String key = (String)pairs.getKey();
            sortByApp.add(key);      
             
        }   
        
        return sortByApp;
    }
    
 
    //按照value对key进行排序
    //reverse = false 按照从小到大的顺序排序
    //reverse = true  按照从大到小的顺序排序
    private Map sortByValue(Map map, final boolean reverse) {
        List list = new LinkedList(map.entrySet());
        Collections .sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                if (reverse) {
                    return -((Comparable) ((Map .Entry)o1).getValue())
                            .compareTo(((Map .Entry)o2).getValue());
                }
                return ((Comparable) ((Map .Entry)o1).getValue())
                        .compareTo(((Map .Entry)o2).getValue());
            }
        });


        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
           result.put(entry.getKey(), entry.getValue());
        }
        return result;
}
0 0
原创粉丝点击