Java 用TreeMap 儲存自定義物件 並按名稱排序
阿新 • • 發佈:2019-02-15
package Map.Demo; import TreeSet.*; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class TreeMapDemo { public static void main(String[] args) { /* * 將學生物件和學生的歸屬地通過鍵與值儲存到map集合中 * * */ TreeMap<Students, String> tm=new TreeMap<Students,String>(new COM()); tm.put(new Students("lisi", 38),"北京"); tm.put(new Students("zhaoliu", 24),"上海"); tm.put(new Students("xiaoqiang", 31),"瀋陽"); tm.put(new Students("wangcai", 28),"大連"); tm.put(new Students("zhaoliu", 24),"鐵嶺"); Iterator<Map.Entry<Students, String>>it=tm.entrySet().iterator(); while(it.hasNext()) { Map.Entry<Students, String>me=it.next(); Students key=me.getKey(); String value=tm.get(key); System.out.println(key.getName()+":"+key.getAge()+"---"+value); } } }
package Map.Demo; import java.util.Comparator; public class COM implements Comparator<Person>{ @Override public int compare(Person o1, Person o2) { int temp=o1.getName().compareTo(o2.getName()); return temp==0?o1.getAge()-o2.getAge():temp; } }