Java集合-HashMap经典面试题

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

注意:要做出这道题必须对集合的体系结构非常的熟悉。 HashMap 本身就是不可排序的,但是该道题偏偏让给HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的, LinkedHashMap,对的,就是他,他是Map 结构,也是链表结构,有序的,更可喜的是他是 HashMap 的子类,我们返回 LinkedHashMap<Integer,User>HashMap 排序,那我们就得想在 API 中有没有这样的 Map 结构是有序的, LinkedHashMap,对的,就是他,他是Map 结构,也是链表结构,有序的,更可喜的是他是 HashMap 的子类,我们返回 LinkedHashMap<Integer,User>即可,还符合面向接口(父类编程的思想)。

但凡是对集合的操作,我们应该保持一个原则就是能用 JDK 中的 API 就有 JDK 中的 API,比如排序算法我们不应该去用冒泡或者选择,而是首先想到用 Collections 集合工具类。


代码实现:

package HashMapDemo;

public class User {
	private String name;
	private int age;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}
	
}

package HashMapDemo;

import java.util.*;
import java.util.Map.Entry;;

public class HashMapTest {
	public static void main(String[] args) {
		HashMap<Integer,User> hm = new HashMap<>();
		User us1 = new User("Mike",22);
		User us2 = new User("Joe",18);
		User us3 = new User("Doe",27);
		User us4 = new User("Rdu",21);
		hm.put(1, us1);
		hm.put(2, us2);
		hm.put(3, us3);
		hm.put(4, us4);
		
		//排序后返回一个LinkedHashMap对象,LinkedHashMap存储的键值对是有序的。
		HashMap<Integer,User> sorthm = sortHashMap(hm);
		Set<Entry<Integer,User>> s = sorthm.entrySet();
		for(Entry<Integer,User> entry : s) {
			System.out.println(entry.getKey()+" : "+entry.getValue());
		}
	}
	
	public static HashMap sortHashMap(HashMap hm) {
		//Set存储所有键值对
		Set<Entry<Integer,User>> set = hm.entrySet();
		
		//转为List因为需要用到Collections自带的sort方法
		List<Entry<Integer,User>> list = new ArrayList<>(set);
		
		//重写sort方法,使用匿名内部类
		Collections.sort(list, new Comparator<Entry<Integer,User>>(){
			@Override
			public int compare(Entry<Integer,User> e1,Entry<Integer,User> e2) {
				// 根据年龄排序
				return e1.getValue().getAge()-e2.getValue().getAge();
			}
		});
		//创建LinkedHashMap对象用来接收List中键值对
		LinkedHashMap<Integer,User> lhm = new LinkedHashMap<>();
		//遍历存储
		for(Entry<Integer, User> entry : list) {
			lhm.put(entry.getKey(), entry.getValue());
		}
		return lhm;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值