Map按照Value值进行排序

1  TreeMap按照value进行排序

public class Testing {

    public static void main(String[] args) {

        HashMap map = new HashMap();
        ValueComparator bvc =  new ValueComparator(map);
        TreeMap sorted_map = new TreeMap(bvc);

        map.put("A",99.5);
        map.put("B",67.4);
        map.put("C",67.4);
        map.put("D",67.3);

        System.out.println("unsorted map: "+map);

        sorted_map.putAll(map);

        System.out.println("results: "+sorted_map);
    }
}

class ValueComparator implements Comparator {

    Map base;
    public ValueComparator(Map base) {
        this.base = base;
    }

    // Note: this comparator imposes orderings that are inconsistent with equals.    
    public int compare(String a, String b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }
}


 输出结果

  unsorted map: {D=67.3, A=99.5, B=67.4, C=67.4}
    results: {D=67.3, B=67.4, C=67.4, A=99.5}


2.HashMap按值进行排序

public class MapUtil
{
    public static > Map 
        sortByValue( Map map )
    {
        List> list =
            new LinkedList>( map.entrySet() );
        Collections.sort( list, new Comparator>()
        {
            public int compare( Map.Entry o1, Map.Entry o2 )
            {
                return (o1.getValue()).compareTo( o2.getValue() );
            }
        } );

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list)
        {
            result.put( entry.getKey(), entry.getValue() );
        }
        return result;
    }
}


 

你可能感兴趣的:(java经验总结)