选择合适的Map集合保存5学生的学号和姓名,然后按照学号的自然顺序的倒序将这些键值对一一打印出来。要求如下: (1)创建TreeMap集合 (2)使用put()方法将学号(“1”“2”“3”“4”“5”)和姓名(“Lucy””John””Smith””Aimee””Amanda”)存储到Map中,存的时候可以打乱顺序观察排序后的效果。 (3)使用map.keySet()获取键的Set集合。 (4)使用Set集合的iterator()方法获得Iterator对象用于迭代键。 (5)使用Map集合的get()方法获取键所对应的值。
package text;
import java.util.*;
public class Text_5 {
public static void main(String[] args) {
TreeMap map = new TreeMap( new MyCompare());
map.put("1", "Lucy");
map.put("2", "John");
map.put("3", "Smith");
map.put("4", "Aimee");
map.put("5", "Amanda");
Set s = map.keySet();
Iterator it = s.iterator();
while(it.hasNext()) {
String key =(String)it.next();
String value = (String)map.get(key);
System.out.println(key+" : "+value);
}
}
}
class MyCompare implements Comparator{
@Override
public int compare(String o1, String o2) {
// TODO 自动生成的方法存根
return o2.compareTo(o1);
}
|