HashMap排序

已知HashMap<Integer,Proson> map,Proson类中有int age,String name属性。请根据Proson中的age进行降序排序。

public class TestMap {

	public static void main(String[] args) {
		
		TestMap t = new TestMap();
		
		HashMap hash = new HashMap<>();
		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 ha = t.Test(hash);
		
		System.out.println("-----------"+ha);
	}
	
	private HashMap Test(HashMap hash){
		
		Set> en = hash.entrySet();
		List> list = new ArrayList<>(en);
		
		Collections.sort(list, new Comparator>() {

			@Override
			public int compare(Entry o1, Entry o2) {
				
				return o1.getValue().getAge()-o2.getValue().getAge();
//				return o1.getKey()-o2.getKey();
			}
			
		});
		
		LinkedHashMap lm = new LinkedHashMap<>();
		
		for (Entry 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;
		}
		
		
		
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值