HashMap根據value值排序 (抄的)

鏈接: HashMap根據value值排序

需要用的時候copy來改一改

/**
 * 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());
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章