zoukankan      html  css  js  c++  java
  • 对Java的Map的Value字段进行排序

      构造TreeMap可以指定Comparator,但是不能对value字段进行排序。如果有需求对Value字段排序,例如map存放的是单词,单词出现次数,怎么按单词次数排序呢?

      可以先将map中的key-value放入list,然后用Collections.sort对list排序,再将排序后的list放入LinkedHashMap,最后返回LinkedHashMap就可以了。LinkedHashMap可是个宝贝,可以通过构造方法制定是按放入的顺序,还是get顺序 排序。LinkedHashMap,稍微修改,可以很容易的实现LRU算法(最近最少使用)。具体的TreeMap 红黑树实现和LinkedHashMap实现还仔细看。

      废话不多说,上代码:

    public class MapUtil {
        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(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>>() {
                public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                    return (o1.getValue()).compareTo(o2.getValue());
                }
            });
    
            Map<K, V> result = new LinkedHashMap<K, V>();
            for (Map.Entry<K, V> entry : list) {
                result.put(entry.getKey(), entry.getValue());
            }
            return result;
        }
    }

    Java 7 Version

        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
            List<Map.Entry<K, V>> list = new LinkedList<>(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) {
                    return (o1.getValue()).compareTo(o2.getValue());
                }
            });
    
            Map<K, V> result = new LinkedHashMap<>();
            for (Map.Entry<K, V> entry : list) {
                result.put(entry.getKey(), entry.getValue());
            }
            return result;
        }

    java 8 version

        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
            Map<K, V> result = new LinkedHashMap<>();
            Stream<Entry<K, V>> st = map.entrySet().stream();
    
            st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));
    
            return result;
        }

    java 8 版本的代码好短啊 ~

    以后做个工具包,像这样的排序直接用工具包使用就可以了。

    参考资料:http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java 

  • 相关阅读:
    Winform中设置BackgroundWorker在取消时关闭后台进程不生效-没有跳出循环
    Ionic中自定义公共模块以及在自定义模块中使用ionic内置模块
    Ionic创建页面以及页面之间跳转、页面添加返回按钮、新增底部页面
    Ionic介绍以及搭建环境、新建和运行项目
    格式化输出(%用法和fomat用法)
    ubuntu1804搜狗输入法乱码问题解决
    python测试网站访问速度
    linux常用命令手册
    docker打包flask简单程序
    docker命令集锦
  • 原文地址:https://www.cnblogs.com/liu-qing/p/3983496.html
Copyright © 2011-2022 走看看