黑马程序员-JavaAPI-16天-7(TreeMap练习)
package string.test; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeMap; /* * * 需求:对学生对象的年龄经行升序排序 * * 因为数据是以键值对形式存在的。 * 所以要使用可以排序的Map集合。TreeMap * * 定义一个对Student的排序类StuNameComparator 要求安名称进行排序 如果名称相同就按年龄进行排序 */ class StuNameComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { int num = o1.getName().compareTo(o2.getName()); if (num == 0) { return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge())); }// TODO Auto-generated method stub return num; } } public class MapDemo5 { public static void main(String[] args) { Map<Student, String> map = new TreeMap<Student, String>(new StuNameComparator()); map.put(new Student("zhangsan", 20), "beijing"); map.put(new Student("lisi", 21), "tianjing"); // map.put(new Student("lisi", 21), // "guangzhou");会把上面的的value替换掉(应为存入了相同的Key) map.put(new Student("wangwu", 22), "hunan"); map.put(new Student("zhaoliu", 27), "hubei"); map.put(new Student("zhaoliu", 23), "hubei"); Set<Map.Entry<Student, String>> keyEntry = map.entrySet(); Iterator<Map.Entry<Student, String>> me = keyEntry.iterator(); while (me.hasNext()) { Map.Entry<Student, String> entry = me.next(); System.out.println("姓名:" + entry.getKey().getName() + ",年龄:" + entry.getKey().getAge() + ",地址:" + entry.getValue()); } } } /* * 以上案列用到了16-6中的学生类 */