TreeMap 實作 NavigableMap,底層為紅黑樹。它能:
Comparator 自動排序。import java.util.Iterator;
import java.util.TreeMap;
import cn.itcast.p2.bean.Student;
import cn.itcast.p3.comparator.ComparatorByName;
public class TreeMapDemo {
public static void main(String[] args) {
// 依學生姓名排序
TreeMap<Student, String> tm = new TreeMap<>(new ComparatorByName());
tm.put(new Student("lisi", 38), "北京");
tm.put(new Student("zhaoliu", 24), "上海");
tm.put(new Student("xiaoqiang", 31), "瀋陽");
tm.put(new Student("wangcai", 38), "大連");
tm.put(new Student("zhaoliu", 24), "鐵嶺"); // Key 相同,值覆蓋
Iterator<Student> it = tm.keySet().iterator();
while (it.hasNext()) {
Student key = it.next();
String value = tm.get(key);
System.out.println(key.getName() + ":" + key.getAge() + "--" + value);
}
}
}

輸出順序按姓名字母序:lisi... xiaoqiang... wangcai... zhaoliu...(重複的 zhaoliu 只保留最後一筆)。
Comparable 或傳入 Comparator。compareTo 回傳 0),新 Value 會覆蓋舊值。