练习:把学生名与考试分数录入到Map中,并按照分数显示前三名学生的名字

版权声明:此文为本人所写,严禁版权侵占行为。未经博主允许不可转载。 https://blog.csdn.net/Abby_lxf/article/details/89039723
package exce;

import java.util.*;

public class ExceStudent {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void main(String[] args) {
		Map map = new TreeMap();
		map.put("小明",89);
		map.put("小花",23);
		map.put("小石",59);
		map.put("小黄",98);
		map.put("小红",97);
		//System.out.println(map);
		Set set = map.entrySet();
		List list = new ArrayList();
		for(Object str : set) {
			Map.Entry entry = (Map.Entry)str;
			list.add(entry);
		}
		
		Collections.sort(list, new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				if(o1 instanceof Map.Entry && o2 instanceof Map.Entry) {
					Map.Entry m1 = (Map.Entry) o1;
					Map.Entry m2 = (Map.Entry) o2;
					return -((Integer)m1.getValue()).compareTo((Integer)m2.getValue());				
				}
				return 0;
			}
		});
		
		
		for (int i = 0; i < 3; i++) {
			System.out.println((Map.Entry)list.get(i));
		}

	}

}

猜你喜欢

转载自blog.csdn.net/Abby_lxf/article/details/89039723