COMPLEX-B

导航

集合面试题

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

public class Fund {
	
	public static void main(String[] args) {
		HashMap<Integer, User> map  = new HashMap<>();
		map.put(1, new User("mike", 12));
		map.put(5, new User("lili", 13));
		map.put(2, new User("lisa", 14));
		map.put(3, new User("lusi", 15));
		map.put(6, new User("lusa", 15));
		System.out.println(map);
		HashMap<Integer, User> newMap = sortMap2(map);
		System.out.println(newMap);
	
	}
	
	public static HashMap<Integer, User> sortMap2(HashMap<Integer, User> map) {
		List<Entry<Integer, User>> entry = new ArrayList<>(map.entrySet()); // 将键值对放入list中以便对其排序
		entry.sort(new Comparator<Entry<Integer, User>>() { // 实现Comparator接口实现排序功能
			@Override
			public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
				return o1.getValue().getAge() - o2.getValue().getAge();
			}
		});
		
		LinkedHashMap<Integer, User> sortMap = new LinkedHashMap<>(); // 返回LinkedHashMap确保添加顺序
		for (Entry<Integer, User> en : entry) {
			sortMap.put(en.getKey(), en.getValue());
		}
		
		return sortMap;
	}
}

posted on 2019-05-10 15:01  COMPLEX-B  阅读(124)  评论(0编辑  收藏  举报