/***/* * Exercise two: * Student objects (name, age) have their own place of ownership, since there is a correspondence. * Store student objects and attribution in the Map collection. * Note: The same name as the same age as the duplicate key. Sort from small to large according to the age of the students. * If you want to sort students by their names? */ Public classPractise2 { Public Static voidMain (string[] args) {/*Create a Map collection*/Map<Student,String> Classmap =NewHashmap<student,string>(); Classmap.put (NewStudent ("Xiao Ming", 15), "Shanghai"); Classmap.put (NewStudent ("Xiao Li", 15), "Shenyang"); Classmap.put (NewStudent ("Xiao Xu", 13), "Wuhan"); Classmap.put (NewStudent ("Xiao Ming", 15), "Shanghai");//keys to treat as duplicatesClassmap.put (NewStudent ("Every Day", 14), "Wuhan"); Classmap.put (NewStudent ("just", 12), "Hebei"); /*sort, thought treeset, comparatively simple, sorted by name, sorted by age for Nature*/Map<Student,String> Classtreemap =NewTreemap<student,string> (NewComparator<student>() {@Override Public intCompare (Student O1, Student O2) {inttemp =o1.getname (). CompareTo (O2.getname ()); returnTemp==0?O1.compareto (O2): temp; } }); Classtreemap.put (NewStudent ("Xiao Ming", 15), "Shanghai"); Classtreemap.put (NewStudent ("Xiao Li", 15), "Shenyang"); Classtreemap.put (NewStudent ("Xiao Xu", 13), "Wuhan"); Classtreemap.put (NewStudent ("Xiao Ming", 15), "Shanghai");//keys to treat as duplicatesClasstreemap.put (NewStudent ("Every Day", 14), "Wuhan"); Classtreemap.put (NewStudent ("just", 12), "Hebei"); for(Student stu:classTreeMap.keySet ()) {System.out.println (STU); } /*the way map turns into list*/List<map.entry<student, string>> list =NewArraylist<map.entry<student, string>>(Classtreemap.entryset ()); for(Entry ent:list) {System.out.println (Ent.getkey ()); System.out.println (Ent.getvalue ()); } }}
TreeMap sorting function, construction method