Map的value值降序排序与升序排序(java) - Go语言中文社区

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


本文为原创博客,仅供技术学习使用。未经允许,禁止转载

程序

package test;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


public class Test {
    public static Map<Integer, Double> Probs = new TreeMap<Integer, Double>();
    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<Integer, Double> 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<Integer, Double> entry : Probs.entrySet()) {
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
        }

    }
    //降序排序
    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;
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
    //升序排序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAscending(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;
            }
        });

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

}

输出结果


这里写图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qy20115549/article/details/79675007
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 20:53:48
  • 阅读 ( 1083 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢