Java中Map根据键(Key)和值(Value)进行排序

按键排序

可以直接使用TreeMap(默认按照键的升序)


Map<Integer, Person> map = new HashMap<Integer, Person>();
TreeMap treemap = new TreeMap(map);

按值排序

假设已知一个HashMap<Integer,Person>集合, Person有username(String)和 age(int)属性,现在要按照Person的年龄对这个HashMap进行排序。

		HashMap<Integer,Person> hashMap = new HashMap<>();
		hashMap.put(2,new Person("111",20));
		hashMap.put(1,new Person("222",40));
		hashMap.put(3,new Person("333",10));
		hashMap.put(5,new Person("444",30));
		hashMap.put(6,new Person("555",2));
		
		//拿到map的键值对集合
		Set<Map.Entry<Integer,Person>> set = hashMap.entrySet();
		
		//将这个set集合转为list集合为了使用工具类的排序方法
		List<Map.Entry<Integer,Person>> list = new ArrayList<>(set);
		
		//排序
		Collections.sort(list, new Comparator<Map.Entry<Integer, Person>>() {

					@Override
					public int compare(Map.Entry<Integer, Person> o1, Map.Entry<Integer, Person> o2) {
						return o2.getValue().getAge()-o1.getValue().getAge();  //降序排序,如果要升序就用前面减后面
					}
				}

		);
		
		//重新装入LinkedHashMap中
		LinkedHashMap<Integer,Person> linkedHashMap = new LinkedHashMap<>();
		for (Map.Entry<Integer,Person> entry:list ) {
			linkedHashMap.put(entry.getKey(),entry.getValue());
		}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值