zoukankan      html  css  js  c++  java
  • HashMap根据value值排序

    /**
    * hashMap排序
    * @author lizhibiao
    * @date 2018/12/3 11:47
    */
    public class TestHashMapCollections
    {
    public static void main(String[] args)
    {
    Map<String, Integer> map = new HashMap<>();
    map.put("王二", 8);
    map.put("沈吴", 2);
    map.put("小菜", 3);
    map.put("大鸟", 1);

    Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
    for (Map.Entry s : entrySet)
    {
    System.out.println(s.getKey()+"--"+s.getValue());
    }

    System.out.println("============排序后============");

    //////借助list实现hashMap排序//////

    //注意 ArrayList<>() 括号里要传入map.entrySet()
    List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
    {
    @Override
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
    {
    //按照value值,重小到大排序
    // return o1.getValue() - o2.getValue();

    //按照value值,从大到小排序
    // return o2.getValue() - o1.getValue();

    //按照value值,用compareTo()方法默认是从小到大排序
    return o1.getValue().compareTo(o2.getValue());
    }
    });

    //注意这里遍历的是list,也就是我们将map.Entry放进了list,排序后的集合
    for (Map.Entry s : list)
    {
    System.out.println(s.getKey()+"--"+s.getValue());
    }

    }
    }


    输出结果如下:
    沈吴--2
    大鸟--1
    小菜--3
    王二--8
    ============排序后============
    大鸟--1
    沈吴--2
    小菜--3
    王二--8


    有疑问,扫我二维码添加微信,欢迎骚扰!
    坚持做一件事,一起学习。


  • 相关阅读:
    Python基础之公共方法
    Python基础之字符串
    Python基础之字典
    Python基础之元组
    Python基础之列表
    Python基础之函数和模块
    Python基础之if判断,while循环,循环嵌套
    Python基础之注释,算数运算符,变量,输入和格式化输出
    Mapreduce实例——二次排序
    Mapreduce实例——Reduce端join
  • 原文地址:https://www.cnblogs.com/lizb0907/p/10060349.html
Copyright © 2011-2022 走看看