38 Map的value值降序排序与升序排序(java)


public class Test {
    public static Map Probs = new TreeMap();
    public static void main(String[] args) {
        Probs.put(1, 0.5);
        Probs.put(2, 1.5);
        Probs.put(3, 0.2);
        Probs.put(4, 10.2);
        Probs = sortByValueDescending(Probs);
        System.out.println("基于value值的降序,排序输出结果为:");
        for (Map.Entry entry : Probs.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }
        System.out.println();
        System.out.println("基于value值的升序,排序输出结果为:");
        Probs = sortByValueAscending(Probs);
        for (Map.Entry entry : Probs.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

    }
    //降序排序
    public static > Map sortByValueDescending(Map map)
    {
        List> list = new LinkedList>(map.entrySet());
        Collections.sort(list, new Comparator>()
        {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map result = new LinkedHashMap();
        for (Map.Entry entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
    //升序排序
    public static > Map sortByValueAscending(Map map)
    {
        List> list = new LinkedList>(map.entrySet());
        Collections.sort(list, new Comparator>()
        {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return compare;
            }
        });

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











你可能感兴趣的:(38 Map的value值降序排序与升序排序(java))