TreeMap和TreeSet对象排序

package Tips;

/**
 * 保证TreeMap的键有序有两种方法:
 * 自然排序:该键的类实现Comparable即重写compareTo方法,创建TreeMap不用特殊处理
 * 定制排序:实现Comparator接口即重写compare方法,创建TreeMap时传入该实现类
 */

import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

class Person implements Comparable {
    public String name;
    public int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

    @Override
    public int compareTo(Person person) {
        return this.name.compareTo(person.name);
    }
}

class AscAgeComparator2 implements Comparator {
    public int compare(Person p1, Person p2) {
        return p1.age - p2.age;
    }
}

public class TreeMapSort {

    public static void main(String[] args) {
        Person p1 = new Person("Zera", 23);
        Person p2 = new Person("Jerry", 19);
        Person p3 = new Person("Tonny", 30);

        System.out.println("TreeMap自然排序:");
        Map map1 = new TreeMap<>();
        map1.put(p1, 5);
        map1.put(p2, 6);
        map1.put(p3, 7);
        System.out.println(map1);

        System.out.println("TreeMap定制排序:");
        Map map2 = new TreeMap<>(new AscAgeComparator2());
        map2.put(p1, 5);
        map2.put(p2, 6);
        map2.put(p3, 7);
        System.out.println(map2);

        System.out.println("TreeSet自然排序:");
        Set set1 = new TreeSet<>();
        set1.add(p1);
        set1.add(p2);
        set1.add(p3);
        System.out.println(set1);

        System.out.println("TreeSet定制排序:");
        Set set2 = new TreeSet<>(new AscAgeComparator2());
        set2.add(p1);
        set2.add(p2);
        set2.add(p3);
        System.out.println(set2);
    }

}

你可能感兴趣的:(TreeMap和TreeSet对象排序)