1 @org.junit.Test 2 public void TestTreeMap2(){ 3 Comparator comparator=new Comparator() { 4 @Override 5 public int compare(Object o1, Object o2) { 6 if (o1 instanceof Student && o2 instanceof Student){ 7 Student stu1=(Student)o1; 8 Student stu2=(Student)o2; 9 int i=stu1.getName().compareTo(stu2.getName()); 10 if(i==0){ 11 return stu1.getAge().compareTo(stu1.getAge()); 12 } 13 return i; 14 } 15 return 0; 16 } 17 }; 18 19 20 Map<Student,Integer> treeMap = new TreeMap<>(comparator); 21 treeMap.put(new Student("aaa",12), 12); 22 treeMap.put(new Student("xxx",15), 56); 23 treeMap.put(new Student("fff",14), 111); 24 treeMap.put(new Student("hhh",15), 12); 25 treeMap.put(new Student("bbb",21), 89); 26 treeMap.put(new Student("bbb",19), 15); 27 28 Set entry=treeMap.entrySet(); 29 for (Object obj:entry){ 30 Map.Entry e=(Map.Entry)obj; 31 System.out.println(e); 32 } 33 34 35 }