zoukankan      html  css  js  c++  java
  • map集合根据value值排序

    public class MapSortedDemo {
    public static void main(String[] args) {
    Map map = new HashMap<>();
    map.put(1, "22");
    map.put(2, "able");
    map.put(3, "disk");
    map.put(4, "banana");
    map.put(5, "001");
    sortMap(map);
    }

    /**
    * map 集合根据value值排序
    *
    * @param map
    * @return
    */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortMap(Map map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    list.sort((o1, o2) -> {
    // 按照 value进行排序
    // return (o2.getValue()).compareTo(o1.getValue()); // 20 ,3,1 倒叙
    return (o1.getValue()).compareTo(o2.getValue()); // 1 ,3,20 正序
    // 按照key 进行排序
    // return ((String) o1.getKey()).compareTo((String) o2.getKey()); // k1 ,k2,k3 正序
    // return ((String) o2.getKey()).compareTo((String) o1.getKey()); // k3 ,k2,k1 倒叙
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
    result.put(entry.getKey(), entry.getValue());
    }
    System.out.println("result = " + result);
    return result;
    }
    }
    运行:
    result = {5=001, 1=22, 2=able, 4=banana, 3=disk}
    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    字符串与指针{学习笔记}
    selenium 测试脚本
    多维数组与指针{笔记}
    SQL注入常用语句{笔记}
    C语言指针{学习笔记}
    字符编码
    移动窗体
    TreeView树形结构
    未能找到元数据文件解决办法
    gridview分页的问题
  • 原文地址:https://www.cnblogs.com/d0minic/p/14072228.html
Copyright © 2011-2022 走看看