zoukankan      html  css  js  c++  java
  • java8 map根据key或者value进行排序

    转自:https://www.jb51.net/article/169242.htm
    map根据key或者value进行排序

    Map<String,BigDecimal> map =new HashMap<>();
    map.put("one", 0.08);
    map.put("two", 0.1);
    map.put("three", 0.2);
    map.put("four", 0.91);
    

    需要对这个map根据value值倒序排序,下面给出工具类:

      public <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
     
        map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByValue()
                .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
      }
    

    当然如果我们想根据map的key进行排序,需要对上面的工具类进行小小的修改,代码如下:

     public <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {
        Map<K, V> result = new LinkedHashMap<>();
     
        map.entrySet().stream()
            .sorted(Map.Entry.<K, V>comparingByKey()
                .reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
      }
    

    我们可以看到,如果我们需要根据key排序,就需要让key 继承 Comparable ,也就说我们需要对待排序的字段继承 Comparable接口。另一个问题就是,上面的这种写法排序效果是 降序排序,如果我们需要升序排序的话,只需要将上面的.reversed()关键字限制去掉即可。

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

    通用map的key排序

        public static <K extends String, V> Map sortMapKey(Map<K, V> map) {
            List<Map.Entry<K, V>> list = new ArrayList(map.entrySet());
            list.sort((o1, o2) -> o2.getKey().length() - o1.getKey().length());
            Map<K, V> linkedMap = new LinkedHashMap<>();
            //list<map>转map,博主不会,如果有大神看到,麻烦评论里教一下
            for (Map.Entry<K, V> entry : list) {
                linkedMap.put(entry.getKey(), entry.getValue());
            }
            return linkedMap;
        }
    
  • 相关阅读:
    天堂Lineage(單機版)從零開始架設教學 Installing Lineage 3.52 Server
    /dev/random vs /dev/urandom
    Linux Interactive Exploit Development with GDB and PEDA
    Python : Polymorphism
    Python : Data Encapsulation
    Using Keyboard Navigation
    Capture pictures using Jpython
    Java并发编程:volatile关键字解析
    java 资料收集
    解决ubuntu侧边栏固定应用单击无反应的问题
  • 原文地址:https://www.cnblogs.com/cchilei/p/13152615.html
Copyright © 2011-2022 走看看