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

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

作者:互联网

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));
		}

	}

}

 

标签:Map,考试分数,map,list,学生,put,Entry,public
来源: https://blog.csdn.net/Abby_lxf/article/details/89039723