JavaSE—Comparable interface and Comparator

[JavaSE]—Comparable interface and comparator comparator

1. Comparable interface

1. Definition of Comparable Interface

image-20210921124851326 It can be seen that this interface is defined through generics, and its function is to specify the sorting rules of a certain object.

Return value:

1: means greater than
-1: indicates less than
0: Indicates equal

2. Actual Case

Reference to the following:

Copyright Statement: This article is an original article by CSDN blogger "Nanhuai Bei'an" and follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.
Original link: https://blog.csdn.net/nanhuaibeian/article/details/104169002

Design a student class that contains name, age, and grades, and generate an object array, which is required to be sorted from high to low by grade. If the grades are equal, sort by age from low to high.
At this time, it would be troublesome to write the sorting operation directly, so you can use the sort() method in the Arrays class to perform the sorting operation.

import java.util.Arrays;

class Student implements Comparable<Student>{//Specify the type as Student
    private String name;
    private int age;
    private float score;
    public Student(String name,int age,float score){
        this.name = name;
        this.age = age;
        this.score = score;
    }
    public String toString(){
        return name + "\t\t" + age + "\t\t" + score;
    }
    public int compareTo(Student stu){
        //Override the compareTo() method to implement the application of sorting rules
        if (this.score>stu.score){
            return -1;
        }else if(this.score < stu.score){
            return 1;
        }else {
            if (this.age > stu.age){
                return 1;
            }else if (this.age<stu.age){
                return -1;
            }else {
                return 0;
            }
        }
    }

}
public class Root{
    public static void main(String[] args) {
        Student[] stu = {new Student("stu1",20,90.0f),
        new Student("stu2",22,90.0f),
        new Student("stu3",20,70.0f),
        new Student("stu4",34,98)};
        Arrays.sort(stu);
        for (Student x:stu){
            System.out.println(x);
        }
    }
}

image-20210921125215145

3. Sorting principle of comparator

The blogger here writes so well that I can’t help but take notes and copy down the homework.

The sorting process is actually the binary tree sorting method in the data structure. Sorting is performed through the binary tree, and then the contents are read out in sequence using in-order traversal.

image-20210921125639785

image-20210921125649910

class BinaryTree{
    class Node{//Declare a node class
        private Comparable data; //Save specific content
        private Node left;
        private Node right;
        public void addNode(Node newNode){
            //Determine whether to place it in the left subtree or the right subtree
            if(newNode.data.compareTo(this.data)<0){
                if(this.left == null){//Place it in the left subtree
                    this.left = newNode;
                }else {
                    this.left.addNode(newNode);
                }
            }
            if (newNode.data.compareTo(this.data)>=0){
                if(this.right == null){ //Place it in the right subtree
                    this.right = newNode;
                }else {
                    this.right.addNode(newNode);
                }
            }
        }
        public void printNode(){//In-order traversal is used when outputting
            if (this.left != null){//Output the left subtree first
                this.left.printNode();
            }
            System.out.print(this.data + "\t");//Then output the root node
            if (this.right !=null){
                this.right.printNode();
            }
        }
    }
    private Node root;
    public void add(Comparable data){
        Node newNode = new Node(); //Declare a root node every time a new content is passed in
        newNode.data = data;
        if(root==null){
            root = newNode;//If it is the first element, set it to the root element
        }else{
            root.addNode(newNode);//Determine whether the node is placed in the left subtree or the right subtree
        }
    }
    public void print(){//Output node
        this.root.printNode();
    }
}
public class Test{
    public static void main(String[] args) {
        BinaryTree bt = new BinaryTree();
        bt.add(8);
        bt.add(3);
        bt.add(3);
        bt.add(10);
        bt.add(9);
        bt.add(1);
        bt.add(5);
        bt.add(5);//Add repeated elements
        System.out.println("Result after sorting:");
        bt.print();
    }
}

Second, Comparator

1. Introduction

  • comparator is an interface in javase, located under the java.util package. This interface is extremely abstract. It is necessary to master the use of this interface.
  • Most articles tell you that comparator is used for sorting, but I want to say that sorting is one of the functions that comparator can achieve. It is not limited to sorting

2. Usage Scenario

  1. Sort, you need to compare two objects which are ranked first and which are ranked last (sorting can also let the class implement the Comparable interface, and after implementation, instances of this class also have the ability to sort).
  2. Group needs to compare whether two objects belong to the same group.

3. Sorting scene

? If the objects in the List or array do not implement the Comparable interface, then the caller needs to set a Compartor for the array or List that needs to be sorted. The compare method of the Compartor is used to tell the code how to compare the two instances, and then based on the comparison The results are sorted.

https://www.cnblogs.com/MrYuChen-Blog/p/14012428.html

4. But one condition sorting

①Dog base class
public class Dog {
    public int age;
    public String name;
    public String num;

    public Dog(int age, String name, String num) {
        this.age = age;
        this.name = name;
        this.num = num;
    }

    public Dog() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "age=" + age +
                ", name='" + name + ''' +
                ", num='" + num + ''' +
                '}';
    }
}
②Single condition sorting test
import java.text.Collator;
import java.util.*;

public class OneSort {

    public static void main(String[] args) {

        List<Dog> dogList= new ArrayList<Dog>(){
            {
                add(new Dog(5, "DogA","001"));
                add(new Dog(5, "DogB","002"));
                add(new Dog(5, "DogC","003"));
                add(new Dog(9, "DogA","004"));
                add(new Dog(35, "DogF","005"));
                add(new Dog(74, "DogG","006"));
            }
        };

        test1(dogList);
        System.out.println("Give the dogs in descending order of age: " + dogList);

        test2(dogList);
        System.out.println("Sort the dogs by name: " + dogList);
    }

    /**
     *Single condition sorting
     */

    public static void test1(List a){
        Collections.sort(a, new Comparator<Dog>() {
            //Implement the compare(T o1, To2) method, returning positive numbers, zero, and negative numbers each representing greater than, equal to, or less than
            @Override
            public int compare(Dog o1, Dog o2) {
                return o2.age - o1.age; //Sort rule----ascending order
            }
        });
    }

    public static void test2(List a){
        //Sort by name
        Collator comparator = Collator.getInstance(Locale.CANADA);

        Collections.sort(a, new Comparator<Dog>() {
            @Override
            public int compare(Dog o1, Dog o2) {
                return comparator.compare(o1.getName(),o2.getName());
            }
        });

    }
}
③Lambda
/**
     *Use Lambda expressions to optimize comparator code (single condition sorting)
     */
    @Test
    public void test3() {
        //Sort the student collection by age
        Collections.sort(list,(s1, s2) -> (s1.getAge() - s2.getAge()) );
    }

5. Multi-condition sorting

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SecondSort {

    public static void main(String[] args) {
        List<Dog> dogList= new ArrayList<Dog>(){
            {
                add(new Dog(5, "DogA","001"));
                add(new Dog(5, "DogB","002"));
                add(new Dog(5, "DogC","003"));
                add(new Dog(9, "DogA","004"));
                add(new Dog(35, "DogF","005"));
                add(new Dog(74, "DogG","006"));
            }
        };

        test1(dogList);
        System.out.println("Age multiple conditions: " + dogList);
    }

    public static void test1(List a){
        Collections.sort(a, new Comparator<Dog>() {

            @Override
            public int compare(Dog o1, Dog o2) {
                int flag;
                // Prefer sorting by age in ascending order
                flag = o1.getAge()-o2.getAge();
                if(flag==0){
                    // If age is sorted in descending order by number
                    flag = o2.getNum().compareTo(o1.getNum());
                }
                return flag;
            }
        });
    }
}