|
C语言趣味程序百例精解之java实现(96)选美比赛
程序:
import java.util.*;
public class Test96{
public static void main(String args[]){
int k=1;
int m[]=new int[8];
HashMap< Integer,Integer> datas = new HashMap< Integer,Integer>(){{
put(1, 5);
put(2, 3);
put(3, 4);
put(4, 7);
put(5, 3);
put(6,5);
put(7,6);
}};
System.out.println("选手序号: 1, 2, 3, 4, 5, 6, 7 ");
System.out.println("选手得分:5, 3, 4, 7, 3, 5, 6 ");
Map.Entry< Integer,Integer>[] b=getSortedHashtableByValue(datas);
for(int i=0;i< b.length;i++){
if(i!=0&&(b.getValue()>b[i-1].getValue())) k++;
m[b.getKey()]=k;
}
System.out.print("选手名次: ");
for(int i=1;i<=7;i++)
System.out.print(m+", ");
}
/**
* @param h
* @return
* 实现对map按照value升序排序
*/
@SuppressWarnings("unchecked")
public static Map.Entry[] getSortedHashtableByValue(Map h) {
Set set = h.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
return key1.compareTo(key2);
}
});
return entries;
}
/**
* @param h
* @return
* 实现对map按照key排序
*/
@SuppressWarnings("unchecked")
public static Map.Entry[] getSortedHashtableByKey(Map h) {
Set set = h.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Object key1 = ((Map.Entry) arg0).getKey();
Object key2 = ((Map.Entry) arg1).getKey();
return ((Comparable) key1).compareTo(key2);
}
});
return entries;
}
}
C:\t>java Test96
选手序号: 1, 2, 3, 4, 5, 6, 7
选手得分:5, 3, 4, 7, 3, 5, 6
选手名次: 3, 1, 2, 5, 1, 3, 4, |
|