黑马程序员-JavaAPI-16天-7(TreeMap练习)
2013-03-20 10:39
483 查看
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中的学生类 */
相关文章推荐
- 黑马程序员-JavaAPI-16天-8(TreeMap练习-字母出现的次数)
- 黑马程序员-JavaAPI-16天-6(Map练习)
- 黑马程序员-JavaAPI-16天-3(Map共性方法)
- 黑马程序员-JavaAPI-16天-9(Map扩展)
- 黑马程序员-JavaAPI-16天-1(Map概述)
- 黑马程序员-JavaAPI-16天-2(Map子类对象特点)
- 黑马程序员-JavaAPI-16天-4(Map-keySet)
- 黑马程序员-JavaAPI-16天-5(Map-entrySet)
- 黑马程序员&mdash;Java基础(接口,类,抽象类综合小练习)
- 黑马程序员-Java if语句练习-暴露的基础小问题
- 黑马程序员_Java基础[14]_模版设计模式、习题练习
- 黑马程序员——Java练习笔记——面向对象
- 黑马程序员_日记59_TreeMap自定义对象练习
- 黑马程序员-----java基础----API(二)
- 黑马程序员----------java基础API之String类的介绍和使用
- 黑马程序员——Java练习笔记——环境变量
- 黑马程序员_Java常用类API
- 黑马程序员__Java中API之StringBuffered
- 黑马程序员 java中的API总结
- 黑马程序员-Java API-day13