HashMap排序 发表于 2016-06-30 | 分类于 Java 概述面试的时候遇到过这样一道算法题,已知HashMap map,User类中有int age,String name属性。请根据User中的age进行降序排序。我们知道HashMap是没有顺序的,这里应该怎么处理呢?回来后想想应该用LinkedHashMap,LinkedHashMap是有顺序的而且是继承HashMap。 具体实现12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061public class TestMap { public static void main(String[] args) { TestMap t = new TestMap(); HashMap<Integer, User> hash = new HashMap<>(); //根据User的年龄进行排序 hash.put(1, new User(22, "张三")); hash.put(2, new User(19, "李四")); hash.put(3, new User(23, "王五")); hash.put(4, new User(18, "Tom")); HashMap<Integer, User> ha = t.Test(hash); System.out.println("-----------"+ha); } private HashMap<Integer, User> Test(HashMap<Integer, User> hash){ Set<Entry<Integer, User>> en = hash.entrySet(); List<Entry<Integer, User>> list = new ArrayList<>(en); //把排序好的放进List里面 Collections.sort(list, new Comparator<Entry<Integer, User>>() { @Override public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) { return o1.getValue().getAge()-o2.getValue().getAge();// return o1.getKey()-o2.getKey(); } }); //再把排序好的LIst遍历到LinkedHashMap LinkedHashMap<Integer, User> lm = new LinkedHashMap<>(); for (Entry<Integer, User> entry : list) { lm.put(entry.getKey(),entry.getValue()); } return lm; } static class User{ public User(int age, String name) { this.age = age; this.name = name; } int age; String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }} ------ 本文结束 ------ 版权声明 文章作者: 周 康 发布时间: 2016年06月30日 - 14:06 原始链接: http://Kanging.github.io/2016/06/30/HashMap算法/ 许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。