TreeMap, similar to TreeSet, allows you to sort the elements in the collection while preserving the uniqueness of the elements.
It should be noted that comparable (implement interface, remember to overwrite Comparato method), comparator use.
1 ImportJava.util.Iterator;2 ImportJava.util.TreeMap;3 4 Importcn.itcast.p2.bean.Student;5 ImportCn.itcast.p3.comparator.ComparatorByName;6 7 Public classTreemapdemo {8 9 Public Static voidMain (string[] args) {Tentreemap<student,string> TM =NewTreemap<student,string> (Newcomparatorbyname ()); One ATm.put (NewStudent ("Lisi", 38), "Beijing"); -Tm.put (NewStudent ("Zhaoliu", 24), "Shanghai"); -Tm.put (NewStudent ("Xiaoqiang", 31), "Shenyang"); theTm.put (NewStudent ("Wangcai", 38), "Dalian"); -Tm.put (NewStudent ("Zhaoliu", 24), "Tieling"); - -Iterator<student> it =Tm.keyset (). iterator (); + while(It.hasnext ()) - { +Student key =It.next (); AString value =Tm.get (key); atSystem.out.println (Key.getname () + ":" +key.getage () + "--" +value); - } - - - } - in}
Sub-Interface---TreeMap of the Java Learning Notes map interface