HashMap排序

来源:互联网 发布:信鸽推送demo php 编辑:程序博客网 时间:2024/04/27 19:40

  已知一个 HashMap<Integer,User> 集合,User有name(String)和age(int)属性。请写一个方法实现对HashMap的排序功能,该方法接收 HashMap<Integer,User> 为形参,返回类型为 HashMap<Integer,User> ,要求对 HashMap<Integer,User> 中的User的age倒序排序。排序时key=value键值对不得拆散。

tips:要做出这道题必须对集合的体系结构非常的熟悉。HashMap本身就是不可排序的,但是该道题偏偏让给HashMap排序,那我们就得想在API中有没有这样的Map结构是有序的,LinkedHashMap,对的,局势他,他是Map结构,也是链表结构,有序的,更可喜的是他是HashMap的子类,我们返回LinkedHashMap<Integer,User>即可,还符合面向对象的思想。

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

<pre name="code" class="html"><span style="font-size:18px;">public class HashMapTest {        public static void main(String[] args) {        HashMap<Integer, User> users = new HashMap<Integer, User>();        users.put(1, new User("张三", 25));        users.put(3, new User("李四", 22));        users.put(2, new User("王五", 28));        System.out.println(users);        HashMap<Integer,User> sortHashMap = sortHashMap(users);        System.out.println(sortHashMap);    /**     * 控制台输出内容     * {1=User [name=张三, age=25], 2=User [name=王五, age=28], 3=User [name=李四,age=22]}     *      *        {2=User [name=王五, age=28], 1=User [name=张三, age=25], 3=User [name=李四,age=22]}     */    }    public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {// 首先拿到map 的键值对集合                Set<Entry<Integer, User>> entrySet = map.entrySet();        // 将set 集合转为List 集合,为什么,为了使用工具类的排序方法                List<Entry<Integer, User>> list = new ArrayList<Entry<Integer, User>>(entrySet);                // 使用Collections 集合工具类对list 进行排序,排序规则使用匿名内部类来实现                Collections.sort(list, new Comparator<Entry<Integer, User>>() {            @Override            public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {//按照要求根据User 的age 的倒序进行排                return o2.getValue().getAge() - o1.getValue().getAge();            }        });//创建一个新的有序的HashMap 子类的集合                LinkedHashMap<Integer, User> linkedHashMap = new LinkedHashMap<Integer, User>();//将List 中的数据存储在LinkedHashMap 中                for(Entry<Integer, User> entry : list){            linkedHashMap.put(entry.getKey(), entry.getValue());        }//返回结果        return linkedHashMap;    }}</span>

来源:黑马程序员面试宝典

                                             
0 0
原创粉丝点击