java collection with sorting - Introduction to the comparator of TreeMap


          In this article, we first introduce an example class as a benchmark for comparison:

public class Person{
    private String name;
    private int age;

    public Person(){

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

         As shown above, a simple class is defined: Person, in which there are two Private member variables name and age. (overrides of all getters, setters and toString are omitted)

         If you follow the example of other collections, when using TreeMap for storage (the source code is as follows)

    public static void main(String[] args) {

        TreeSet treeSet = new TreeSet(new SetDemo());
        treeSet.add(new Person("xiaoliu",12));
        treeSet.add(new Person("zhangsan",13));
        treeSet.add(new Person("lisi",14));
        treeSet.add(new Person("wangwu",15));
        treeSet.add(new Person("zhaoxin",16));
        treeSet.add(new Person("delai",17));


... the compiler will report the following errors:

cannot be cast to class java.lang.Comparable

         This is because TreeMap is an ordered set based on Red/Black Tree data structure. It must be provided with an arrangement method before data can be stored in it. Then, the discussion object of the text: comparator is introduced.

Type of comparator:

        1. Internal comparator:

        In the class storing elements, use the Comparable interface to override the compareTo method to implement the permutation method.

        Classes set with internal comparators can be stored directly using TreeMap.

        2. External comparator:

         In the same class class with TreeMap, the Comparator interface is used to overwrite the compare method to implement the permutation method, and when used, the external comparator must be invoked in TreeMap.

How to use the comparator:

        1. Internal comparator:

         As follows, you need to use the Comparable interface first, and then override the compareTo method.

public class Person implements Comparable

          Then, we need to override the compareTo method.

        Here, we choose to sort by the length of the name string

public int compareTo(Object o) {
    Person p = (Person) o;
    if( >{
        return 1;
    }else if( <{
        return -1;
        return 0;

        Tips: if the compiler we use is IDEA, when we use the Comparable interface, we will give a prompt that we need to override the compareTo method. At this time, when the cursor stays on the imperants line, we can directly generate the override template by alt+enter.

        As above, the return values are arranged in descending order when the positive number corresponds to greater than, the negative number corresponds to less than, and the zero corresponds to equal to. Conversely, if the return value is reversed, the TreeMap can be arranged in ascending order.

        After setting, we run it in the main function, and the output is as follows:

[Person{name='zhangsan', age=13}, Person{name='xiaoliu', age=12}, Person{name='wangwu', age=15}, Person{name='delai', age=17}, Person{name='lisi', age=14}]

          It can be seen that the descending order of name is successful. (if the output structure is similar to com.xxxx, the toString method cannot be overridden in the corresponding method)

        2. External comparator:

        The external comparator needs to use the interface in the creation class of TreeMap. The class name of the main function in this paper is SetDemo. Therefore, after adding the use of the interface, it is as follows:

public class SetDemo implements Comparator<Person>

        As mentioned above, the Comparator here must use < > to indicate the corresponding sorting classes, otherwise an error will be reported.

        The second step is to complete the override of compare method

public int compare(Person o1, Person o2) {
    if(o1.getAge() > o2.getAge()){
        return -1;
        return 0;

          As shown above, in comparison, if the return value is positive, it is in ascending order, and if the return value is negative, it is in descending order.

        The third step is to call the comparator we set up in TreeSet.

TreeSet treeSet = new TreeSet(new SetDemo());

        At this point, the results we want can be obtained by running (for example, if the output structure is similar to com.xxxx, the toString method cannot be overridden in the corresponding method)

[Person{name='delai', age=17}, Person{name='zhaoxin', age=16}, Person{name='wangwu', age=15}, Person{name='lisi', age=14}, Person{name='zhangsan', age=13}, Person{name='xiaoliu', age=12}]

        Special note: when external comparator and internal comparator are set at the same time, the priority of external comparator is higher.

Tags: Java

Posted on Wed, 27 Oct 2021 08:08:33 -0400 by silentweed