一、TreeMap自定义排序规则的两种方式
1、概述
2、演示:其key实现Comparable接口
代码演示:
运行结果:
3、演示:采用自定义比较器
代码演示:
运行结果:
4、小结
TreeMap基于二叉树数据结构存储数据,同时实现了SortedMap接口以保障元素顺序存取,默认按照键的升序排序,也可以自定义排序比较器;
TreeMap常用于实现排序的映射列表,在使用TreeMap时其key必须实现Comparable接口或采用自定义的比较器,否则会抛出java.lang.ClassCastExption异常;
package com.zibo.java.february.third;
import java.util.Set;
import java.util.TreeMap;
public class StuTreeMap {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>();
treeMap.put(new Student("大哥",24),"大哥");
treeMap.put(new Student("二哥",23),"二哥");
treeMap.put(new Student("三哥",22),"三哥");
treeMap.put(new Student("四哥",21),"四哥");
Set studentSet = treeMap.keySet();
for (Student student : studentSet) {
System.out.println(student.toString());
}
}
}
// 这里就省略getter和setter方法了
class Student implements Comparable{
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
// 实现Comparable接口在这里也是自定义排序规则
// 如果什么也不写,直接默认return 0的话,只能存储第一个被put的元素
// 注意:升序就这么个写法,不要看网上其他的什么相等返回0,相等的话要返回this.age,否则会出问题
if(age > o.age){
return 1;
}else if(age < o.age){
return -1;
}
return this.age;
}
}
Student{name='四哥', age=21}
Student{name='三哥', age=22}
Student{name='二哥', age=23}
Student{name='大哥', age=24}
package com.zibo.java.february.third;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
public class StuTreeMap2 {
public static void main(String[] args) {
TreeMap treeMap = new TreeMap<>(new Comparator() {
@Override
public int compare(Student2 o1, Student2 o2) {
// 基本和key实现Comparable接口,重写compareTo方法一致
// 升序排序就是这么写的
if(o1.getAge() > o2.getAge()){
return 1;
}else if(o1.getAge() < o2.getAge()){
return -1;
}
// 相等的时候不能返回0
return o1.getAge();
}
});
treeMap.put(new Student2("大哥",24),"大哥");
treeMap.put(new Student2("二哥",23),"二哥");
treeMap.put(new Student2("三哥",22),"三哥");
treeMap.put(new Student2("四哥",21),"四哥");
Set studentSet = treeMap.keySet();
for (Student2 student : studentSet) {
System.out.println(student.toString());
}
}
}
class Student2{
private String name;
private int age;
public Student2() {
}
public Student2(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Student{name='四哥', age=21}
Student{name='三哥', age=22}
Student{name='二哥', age=23}
Student{name='大哥', age=24}
两种方式区别不大,一个是key实现Comparable接口,重写compareTo()方法,另一个是在TreeMap的构造函数中创建new Comparator匿名内部类,重写compare 方法;两者实现的功能都是一样的;注意写法要按照代码演示中写;