[Java learning notes] The Map interface sub-interface --- TreeMap, learning notes --- treemap
Similar to TreeSet, TreeMap can sort elements in a set and maintain the uniqueness of elements.
It should be noted that Comparable (The implementation interface should overwrite the comparaTo method) is used by Comparator.
1 import java. util. iterator; 2 import java. util. treeMap; 3 4 import cn. itcast. p2.bean. student; 5 import cn. itcast. p3.comparator. comparatorByName; 6 7 public class TreeMapDemo {8 9 public static void main (String [] args) {10 TreeMap <Student, String> tm = new TreeMap <Student, string> (new ComparatorByName (); 11 12 tm. put (new Student ("lisi", 38), "Beijing"); 13 tm. put (new Student ("zhaoliu", 24), "Shanghai"); 14 tm. put (new Student ("xiaoqiang", 31), "Shenyang"); 15 tm. put (new Student ("wangcai", 38), "Dalian"); 16 tm. put (new Student ("zhaoliu", 24), "Tieling"); 17 18 Iterator <Student> it = tm. keySet (). iterator (); 19 while (it. hasNext () 20 {21 Student key = it. next (); 22 String value = tm. get (key); 23 System. out. println (key. getName () + ":" + key. getAge () + "--" + value); 24} 25 26 27} 28 29}