用一个map存储学生的学习成绩,学生姓名作为key,成绩作为value

要求:

打印出成绩前三的学生(自学map按value排序的方法)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * 用一个map存储学生的学习成绩,学生姓名作为key,成绩作为value 
 * 打印出成绩前三的学生(自学map按value排序的方法)
 * 
 * @author Administrator
 *
 */
public class Student {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<String,Integer> map = new HashMap<String, Integer>();
		map.put("张学生", 79);
		map.put("李学生", 68);
		map.put("陈学生", 85);
		map.put("刘学生", 99);
		map.put("李学生", 73);
		
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
		Collections.sort(list,new Comparator<Map.Entry<String, Integer>>() {
			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				
				return o2.getValue()-o1.getValue();
			}
		});
		for(Map.Entry<String, Integer> set : list.subList(0, 3)) {
			System.out.println(set);
		}
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_39788493/article/details/80777492