TreeMap中的元素默认按照keys的自然排序排列。(对Integer来说,其自然排序就是数字的升序;对String来说,其自然排序就是按照字母表排序)
如果想实现让元素按自己的想法去进行排序,可以实现Comparable接口之后重写compare接口,在里面书写自己的规则,之后就可以实现自己的功能。
代码:
import java.util.Comparator;
import java.util.TreeMap;
import com.heima.bean.Student;
public class Demo6_TreeMap {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName());
return num == 0 ? s1.getAge() - s2.getAge() : num;
}
});
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("赵六", 26), "上海");
tm.put(new Student("李四", 24), "广州");
tm.put(new Student("王五", 25), "深圳");
System.out.println(tm);
}
private static void demo1() {
TreeMap<Student, String> tm = new TreeMap<>();
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("赵六", 26), "上海");
tm.put(new Student("李四", 24), "广州");
tm.put(new Student("王五", 25), "深圳");
System.out.println(tm);
}
}