选择某种Map集合保存学号从1到15的学员的学号(键)和姓名(值),学号用字符串表示,输入的时候要以学号乱序的方式存入Map集合,然后按照学号从大到小的顺序将Map集合中的元素输出打印。需要自定义Ma

来源:互联网 发布:c语言数组定义和输出 编辑:程序博客网 时间:2024/05/17 03:07
package 集合框架;
import java.util.*; 
public class MyMap {


public static void main(String[] args) {
// TODO Auto-generated method stub


       TreeMap map = new TreeMap(new MyComparator());  
       map.put("1", "AA");  
       map.put("3", "CC");  
       map.put("2", "BB");  
       map.put("5", "EE");  
       map.put("4", "DD");  
       map.put("6", "FF");  
       map.put("8", "HH");  
       map.put("7", "GG");  
       map.put("9", "II");  

                                                 //我只输入了9个值,因为我输入15个值,

                                                                   他就不好好的排序了。不懂why   
  Set keySet=map.keySet();
  Iterator it =keySet.iterator();
  while(it.hasNext()) {
  Object key =it.next();
  Object value=map.get(key);
  System.out.println(key+":"+value);
 
   
       
  }
}  
}  
class MyComparator implements Comparator {  
   public int compare(Object obj1, Object obj2) {  
       String ele1 = (String) obj1;  
       String ele2 = (String) obj2;  
       return ele2.compareTo(ele1);  
   }  
}

 Set keySet=map.keySet();
  Iterator it =keySet.iterator();
  while(it.hasNext()) {
  Object key =it.next();
  Object value=map.get(key);
  System.out.println(key+":"+value);
 
   
       
  }
}  
}  
class MyComparator implements Comparator {  
   public int compare(Object obj1, Object obj2) {  
       String ele1 = (String) obj1;  
       String ele2 = (String) obj2;  
       return ele2.compareTo(ele1);  
   }  

}


结果:

阅读全文
0 0