Comparatorcomparable

The use of natural sorting Comparable

  • Case requirements

    • Store student objects and traverse, create a TreeSet collection and use the no-parameter construction method

    • Requirements: Sort by age from youngest to oldest. If the ages are the same, sort by name in alphabetical order.

  • Implementation steps

    1. Create a TreeSet collection using empty parameter construction

      • Use the TreeSet collection to store custom objects. The no-parameter construction method uses natural sorting to sort the elements.

    2. Custom Student class implements Comparable interface

      • Natural sorting is to let the class to which the element belongs implement the Comparable interface and override the compareTo(T o) method.

    3. Override the compareTo method in the interface

      • When rewriting methods, be sure to note that the sorting rules must be written according to the required primary and secondary conditions.

public class Student implements Comparable<Student>{
    private String name;
    private int age;

    public Student() {
    }

    public Student(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 +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        //Sort according to the age of the object
        //Main judgment conditions: Sort by age from small to large
       //this represents the element currently to be added
        //o represents an element already in the red-black tree
        //Negative number: The function currently to be added is small
        //Positive number: The function to be added currently is large
        //0: Repeat, do not save
        int result = this.age - o.age;
        //Secondary judgment condition: When the age is the same, sort according to the alphabetical order of the name
        result = result == 0 ? this.name.compareTo(o.getName()) : result;
        return result;
    }
}

public class MyTreeSet2 {
    public static void main(String[] args) {
        //Create collection object
        TreeSet<Student> ts = new TreeSet<>();
//Create student object
        Student s1 = new Student("zhangsan",28);
        Student s2 = new Student("lisi",27);
        Student s3 = new Student("wangwu",29);
        Student s4 = new Student("zhaoliu",28);
        Student s5 = new Student("qianqi",30);
//Add students to the collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
//Traverse the collection
        for (Student student : ts) {
            System.out.println(student);
        }
    }
}

The use of comparator sorting Comparator

  • Case requirements

    • Store the teacher object and traverse it, create a TreeSet collection and use the parameterized construction method

    • Requirements: Sort by age from youngest to oldest. If the ages are the same, sort by name in alphabetical order.

  • Implementation steps

    • Use the TreeSet collection to store custom objects. The parameterized construction method uses comparator sorting to sort the elements.

    • Comparator sorting is to let the collection construction method receive the implementation class object of Comparator and override the compare(T o1,T o2) method

    • When rewriting methods, be sure to note that the sorting rules must be written according to the required primary and secondary conditions.

  • Code

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

    public Teacher() {
    }

    public Teacher(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 "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class MyTreeSet4 {
    public static void main(String[] args) {
      //Create collection object
        TreeSet<Teacher> ts = new TreeSet<>(new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                //o1 represents the element to be stored now
                //o2 represents the elements that have been stored in the collection
              
                //main conditions
                int result = o1.getAge() - o2.getAge();
                //Secondary conditions
                result = result == 0 ? o1.getName().compareTo(o2.getName()) : result;
                return result;
            }
        });
//Create teacher object
        Teacher t1 = new Teacher("zhangsan",23);
        Teacher t2 = new Teacher("lisi",22);
        Teacher t3 = new Teacher("wangwu",24);
        Teacher t4 = new Teacher("zhaoliu",24);
//Add the teacher to the collection
        ts.add(t1);
        ts.add(t2);
        ts.add(t3);
        ts.add(t4);
//Traverse the collection
        for (Teacher teacher : ts) {
            System.out.println(teacher);
        }
    }
}

Summary of two comparison methods

  • Summary of two comparison methods

    • Natural sorting: Custom classes implement the Comparable interface, override the compareTo method, and sort according to the return value

    • Comparator sorting: When creating a TreeSet object, pass the Comparator implementation class object, override the compare method, and sort according to the return value.

    • When used, natural sorting is used by default. When natural sorting does not meet current needs, comparator sorting must be used.

  • Rules about return values in both methods

    • If the return value is a negative number, it means that the currently stored element is a smaller value and is stored on the left

    • If the return value is 0, it means that the currently stored element is a duplicate of the element in the collection and is not stored.

    • If the return value is a positive number, it means that the currently stored element is a larger value and is stored on the right

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139,198 people are learning the system