Map 值排序 浮点数

    //升序排序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map)
    {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>()
        {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2)
            {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return compare;

              //return -compare;  //降序排序
            }
        });
        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//调用

Map<String, Float> map = new HashMap<>();

/*

map赋值函数

*/

Map<String, Float> sortByValueDescending = sortByValueDescending(map);
            for (Entry<String, Float> entry : sortByValueDescending.entrySet()) {
                System.out.println(entry.getKey()+"\t"+entry.getValue());
            }

发布了11 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/m0_37762912/article/details/99671240