HashMap排序

已知一个 HashMap<String,Integer>集合。

请写一个方法实现对 HashMap 的排序功能,该方法接收 HashMap<String,Integer>为形参,返回类型为 HashMap<String,Integer>, 要求对 HashMap 中的 User 的 age 倒序进行排序。

排序时 key=value 键值对不得拆散。

注意:要做出这道题必须对集合的体系结构非常的熟悉。

HashMap 本身就是不可排序的,但是该道题偏偏让给 HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的,LinkedHashMap,对的,就是他,他是 Map 结构,也是链表结构,有序的,更可喜的是他是 HashMap 的子类,我们返回 LinkedHashMap<String,Integer>即可,还符合面向接口(父类编程的思想)。

但凡是对集合的操作,我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API,比如排序算法我们不应 该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。

package com.waves.contentunion.controller;

import java.util.*;

/**
 * HashMap 排序
 * @author waves
 * @date 2023/4/18 16:29
 */
public class HashMapSort {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("小明",15);
        map.put("小红",25);
        map.put("小黄",26);
        map.put("小王",12);
        System.out.println("排序前--->" + map);
        LinkedHashMap<String,Integer> map1 = sort(map);
        System.out.println("排序后--->" + map1);
    }

    private static LinkedHashMap<String, Integer> sort(Map<String, Integer> map) {
        //拿到集合map的键值对集合
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        //将set集合转为List集合,转为List是为了更好地使用工具类的排序方法
        List<Map.Entry<String,Integer>> entryList = new ArrayList<>(entrySet);
        // 使用 Collections 集合工具类对 list 进行排序,排序规则使用匿名内部类来实现
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //按照要求根据 年龄 的倒序进行排
                return o2.getValue() - o1.getValue();
            }
        });
        //创建一个新的有序集合
        LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<String,Integer>();
        //将 List 中的数据存储在 LinkedHashMap 中
        for (Map.Entry<String,Integer> user: entryList) {
            linkedHashMap.put(user.getKey(),user.getValue());
        }
        return linkedHashMap;
    }
}

 

posted @ 2023-04-18 17:07  旧歌  阅读(54)  评论(0编辑  收藏  举报