TreeMap 排序重写

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MapSort
{
    private Map<Object, Number> map;
    private TreeMap<Object, Number> sortedMap;
    private TreeMap<Object, Number> descSortedMap;
    public MapSort(Map<Object, Number> map)
    {
        this.map = map;
        this.sortedMap = sortedMap();
        this.descSortedMap = descSortedMap();
    }
    
    public Object[] getSortedMap()
    {
        return sortedMap.keySet().toArray();
    }
    
    public Object[] getDescSortedMap()
    {
        return descSortedMap.keySet().toArray();
    }

    private TreeMap<Object, Number> sortedMap()
    {
        TreeMap<Object, Number> treeMap = new TreeMap<Object, Number>(new Comparator<Object>(){

            public int compare(Object o1, Object o2)
            {
                Number n1 = map.get(o1);
                Number n2 = map.get(o2);
                if (n2.doubleValue() == n1.doubleValue())
                    return o1.hashCode() - o2.hashCode();
                else 
                    return (int)(n1.doubleValue() - n2.doubleValue());
            }});
        
        Iterator it = map.keySet().iterator();
        while(it.hasNext())
        {
            Object key = it.next();
            Number value = map.get(key);
            treeMap.put(key, value);
        }
        
        return treeMap;
    }
    
    private TreeMap<Object, Number> descSortedMap()
    {
        TreeMap<Object, Number> treeMap = new TreeMap<Object, Number>(new Comparator<Object>(){

            public int compare(Object o1, Object o2)
            {
                Number n1 = map.get(o1);
                Number n2 = map.get(o2);
                if (n2.doubleValue() == n1.doubleValue())
                    return o2.hashCode() - o1.hashCode();
                else
                    return (int)(n2.doubleValue() - n1.doubleValue());
            }});
        
        Iterator it = map.keySet().iterator();
        while(it.hasNext())
        {
            Object key = it.next();
            Number value = map.get(key);
            treeMap.put(key, value);
        }
        
        return treeMap;
    }
}





如何对Map进行按值(value)排序?

/**
     * @param h
     * @return
     * 实现对map按照value升序排序
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByValue(Map h) {
        Set set = h.entrySet();
        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
                .size()]);
        Arrays.sort(entries, 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);
            }
        });

        return entries;
    }

你可能感兴趣的:(java)