[Map]利用LinkedHashMap来排序

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

public class HashMapTest {
    public static void main(String[] args) {
        HashMap<Integer, User> users = new HashMap<Integer, User>();
        users.put(1, new User("张三", 25L));
        users.put(3, new User("李四", 22L));
        users.put(2, new User("王五", 28L));
        System.out.println(users);
        HashMap<Integer, User> sortHashMap = sortHashMap(users);
        System.out.println(sortHashMap);
    }

    public static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
        HashMap<Integer, User> linkedHashMap = new LinkedHashMap<Integer, User>();
        Set<Map.Entry<Integer, User>> entrySet = map.entrySet();
        List<Map.Entry<Integer, User>> list = new ArrayList<Map.Entry<Integer, User>>();
        list.addAll(entrySet);
        //根据年龄排倒序
        Collections.sort(list, new Comparator<Map.Entry<Integer, User>>() {
            public int compare(Map.Entry<Integer, User> o1, Map.Entry<Integer, User> o2) {
                if (o1.getValue().getAge() - o2.getValue().getAge() > 0) {
                    return -1;
                } else if (o1.getValue().getAge() - o2.getValue().getAge() < 0) {
                    return 1;
                }
                return 0;
            }
        });
        for (Map.Entry<Integer, User> entry : list) {
            linkedHashMap.put(entry.getKey(), entry.getValue());
        }
        return linkedHashMap;
    }
}
public class User {
    private String username;
    private Long age;

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public User(String username, Long age) {
        this.username = username;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

转载于:https://my.oschina.net/u/3782515/blog/2050404

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值