您的位置:首页 > 其它

方法二:请将你班学生的姓名与考试分数录入到Map中,并按分数从高到低在控制台上打印出来。

2015-09-17 12:43 344 查看
<span style="font-size:18px;">package com.yunhe.shangwu;

//请将你班学生的姓名与考试分数录入到Map中,并按分数从高到低在控制台上打印出来。
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;

public class Stu2 {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("zhangsan", 100);
map.put("lisi", 80);
map.put("mazi", 90);
map.put("wanger", 90);

// 通过.entrySet()的方法把Map类型的转化为Set集合
Set<Entry<String, Integer>> entrySet = map.entrySet();

// 把Set集合转化为List集合
List<Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
entrySet);

for (Entry<String, Integer> temp : list)
System.out.println(temp);// 未排序的结果
System.out.println("--------------------");

// 通过Collections.sort排序
Collections.sort(list, new Comparator<Entry<String, Integer>>() {

@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
// TODO Auto-generated method stub

return o2.getValue() - o1.getValue();
}
});

for (Entry<String, Integer> temp : list)
System.out.println(temp);

}

}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: