前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Map集合排序

Map集合排序

作者头像
会说话的丶猫
发布2020-09-24 10:27:33
8120
发布2020-09-24 10:27:33
举报
public class MapOrder {

    public static void main(String[] args) {
        HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
        hashMap.put("d",11);
        hashMap.put("k",5);
        hashMap.put("l",16);
        hashMap.put("p",7);

        /*Map<String, Integer> result = sortByValue(hashMap,false);

        List<String> list = result.entrySet().stream().map(entry -> entry.getKey())
                .collect(Collectors.toList());

        list.stream().forEach(string ->{
            System.out.println(string);
        });*/

        //sortByValue(hashMap);

        sortTreeMap();

    }

    /**
     * ********************************************************************************************************
     * java8新特性:对map集合排序,根据key或者value操作排序(升序、降序)
     * ********************************************************************************************************
     */

    /**
     * 根据map的key排序
     *
     * @param map 待排序的map
     * @param isDesc 是否降序,true:降序,false:升序
     * @return 排序好的map
     * @author zero 2019/04/08
     */
    public static <String extends Comparable<? super String>,Integer> Map<String,Integer> sortByKey(Map<String,Integer> map, boolean isDesc) {
        Map<String,Integer> result = Maps.newLinkedHashMap();
        if (isDesc) {
            map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByKey().reversed())
                    .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else {
            map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByKey())
                    .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }

    /**
     * 根据map的value排序
     *
     * @param map 待排序的map
     * @param isDesc 是否降序,true:降序,false:升序
     * @return 排序好的map
     * @author zero 2019/04/08
     */
    public static <String, Integer extends Comparable<? super Integer>> Map<String, Integer> sortByValue(Map<String, Integer> map, boolean isDesc) {
        Map<String, Integer> result = Maps.newLinkedHashMap();
        if (isDesc) {
            map.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        } else {
            map.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue())
                    .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        }
        return result;
    }

    /**
     * ********************************************************************************************************
     * 传统方法:对map集合排序,根据key或者value操作排序(升序、降序)
     * ********************************************************************************************************
     */

    //HashMap
    public static void sortByValue(Map<String,Integer> map){
        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) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for(Map.Entry<String,Integer> mapping:list){
            System.out.println(mapping.getKey()+":"+mapping.getValue());
        }
    }



    /**
     *TreeMap:能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,
     *得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。
     */
    public static void sortTreeMap(){
        Map<String,Integer> treeMap = new TreeMap<>(
                new Comparator<String>() {
                    @Override
                    public int compare(String o1, String o2) {
                        return o1.compareTo(o2);
                    }
                }
        );
        treeMap.put("r",11);
        treeMap.put("b",5);
        treeMap.put("a",16);
        treeMap.put("p",7);

        //不用迭代器遍历
        System.out.println("不用迭代器遍历");
        treeMap.entrySet().stream().forEach(entry ->{
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        });
        //用迭代器遍历
        System.out.println("用迭代器遍历");
        Iterator<Map.Entry<String,Integer>> iterator = treeMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Integer> entry = iterator.next();
            System.out.println(entry.getKey() + "---->" + entry.getValue());
        }

    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档