zoukankan      html  css  js  c++  java
  • 集合面试题

    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;
    	}
    }
    
  • 相关阅读:
    linux 删除乱码文件
    snprintf用法
    面试时经常问到的非技术性问题
    vector查找元素
    new 和delete
    python安装
    UIPickerView详解
    设置文本框左边显示的View
    字符串的分割??
    VC++异常捕获??
  • 原文地址:https://www.cnblogs.com/zhz-8919/p/10844487.html
Copyright © 2011-2022 走看看