• 对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 

  • 相关阅读:
    【转】i18n实现前端国际化(实例)
    【转】SQL Pretty Printer for SSMS 很不错的SQL格式化插件
    windows server IIS启用Windows authentication
    【转】命令行下载各种网上各种视频
    解决python “No module named pip”
    【转】excel音标乱码
    【转】自动化部署之jenkins及简介
    【转】右键菜单管理
    【转】C# @作用
    【转】NGen
  • 原文地址:https://www.cnblogs.com/liu-qing/p/3983496.html
Copyright © 2020-2023  润新知