import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; /* * 将学生名和考试成绩录入到MAP中,并按照成绩显示前三名 * * */ public class Test2 { public static void main(String[] args) { TreeMap reporter =new TreeMap(); reporter.put("D9", 99); reporter.put("D2", 92); reporter.put("D8", 19); reporter.put("D4", 39); reporter.put("D5", 59); reporter.put("D3", 79); reporter.put("D1", 69); Collection coll = reporter.values(); List l = new ArrayList(coll); Collections.sort(l,new Comparator(){ @Override public int compare(Object o1, Object o2) { if(o1 instanceof Integer&&o2 instanceof Integer) { Integer i1 = (Integer)o1; Integer i2 = (Integer)o2; return i2.compareTo(i1); } return 0; }}); LinkedHashMap lm = new LinkedHashMap(); Set set = reporter.entrySet(); for(int j=0;j<3;j++){ Integer i = (Integer) l.get(j); Iterator it = set.iterator(); while(it.hasNext()) { Map.Entry entry = (Entry) it.next(); if((Integer)entry.getValue()==i){ lm.put(entry.getKey(), entry.getValue()); } } } System.out.println(lm); } }
解决方案
12
http://stackoverflow.com/questions/8119366/sorting-hashmap-by-values
http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java?page=1&tab=votes#tab-top
http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java?page=1&tab=votes#tab-top
12
可以考虑使用Guava提供的集合框架,MultiMap可以返回任意实现的Map的K-V反转视图(即变成V-K)
16
能否可以考虑将学生民和成绩封装在一起放入list集合,然后直接对成绩进行排序