HashMap 排序

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 已知一个 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<>();       
		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);
	}

	private static HashMap<Integer, User> sortHashMap(HashMap<Integer, User> map) {
		//创建一个新的有序的 HashMap 子类的集合
		LinkedHashMap<Integer,User> newHash=new LinkedHashMap<>();
		// 拿到 map 的键值对集合
		Set<Entry<Integer,User>> tempSet=map.entrySet();	
		// 将 set 集合转为 List 集合,为什么,为了使用工具类的排序方法
		List<Entry<Integer,User>> tempList=new ArrayList(tempSet); 
		// 使用 Collections 集合工具类对 list 进行排序,排序规则使用匿名内部类来实现
		Collections.sort(tempList,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();
			}			
		});
		//将 List 中的数据存储在 LinkedHashMap 中
		for(int i=0;i<tempList.size();i++) {
			newHash.put(tempList.get(i).getKey(), tempList.get(i).getValue());
		}	
		//返回结果
		return newHash;
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值