Comparator and Comparable comparison

Comparable is a sorting interface: If a class implements the Comparable interface, it means “this class supports sorting”.

Comparator is a comparator: If we need to control the order of a certain class, we can create a “comparator of this class” for sorting. Comparable is equivalent to “internal comparator”, and Comparator is equivalent to “external comparator”.

We need to create a List collection containing a list of users and sort them by age of the users from oldest to youngest. The specific implementation code is as follows: Type 1: Implement Comparable<>interface

Write a Person class:

class Person implements Comparable<Person>{

        Integer id;
        String name;
        Integer age;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
        @Override
        public int compareTo(Person o) {
            // Sort by age from oldest to youngest
            return o.getAge()-this.getAge();
        }
    }

Implement the result test:

public static void main(String[] args){
        //Assume that three objects are put in and called directly
        List<Person> pr=new ArrayList<Person>(){<!-- -->{
            add(new Person(1,"huitao1",32));
            add(new Person(2,"huitao2",40));
            add(new Person(3,"huitao3",28));

        }};
        //Very important
        Collections.sort(pr);
        pr.forEach(p->{
            System.out.print(p);
        });
    }

The results are sorted according to 40, 32, 28

Second type: Comparator sorting

Comparable is a comparison method inside the class, while Comparator is a comparator outside the sorting class. Using the Comparator comparator, there is no need to modify the original Person class. You only need to extend a comparator of the Person class. There are two ways to implement Comparator:

  • Create a new Comparator comparator;
  • Use Comparator anonymous class comparator.
static class Person {

        Integer id;
        String name;
        Integer age;

        public Person(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

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

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

Write a comparator class:

static class ToPerson implements Comparator<Person>{

        @Override
        public int compare(Person o1, Person o2) {
            return o1.getAge() - o2.getAge();
        }
    }
public static void main(String[] args){



        List<Person> pr=new ArrayList<Person>(){<!-- -->{
            add(new Person(1,"huitao1",32));
            add(new Person(2,"huitao2",40));
            add(new Person(3,"huitao3",28));

        }};
        //Very important
        Collections.sort(pr,new ToPerson());
        pr.forEach(p->{
            System.out.print(p);
        });
    }

Test Results:

They are 28, 32, and 40 respectively. If you want to go from large to small, you can write it as

static class ToPerson implements Comparator<Person>{

    @Override
    public int compare(Person o1, Person o2) {
        return o2.getAge() - o1.getAge();
    }
}

Access as an anonymous class:

static class Person {

        Integer id;
        String name;
        Integer age;

        public Person(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

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

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
 public static void main(String[] args){



        List<Person> pr=new ArrayList<Person>(){<!-- -->{
            add(new Person(1,"huitao1",32));
            add(new Person(2,"huitao2",40));
            add(new Person(3,"huitao3",28));

        }};
        //Very important
        Collections.sort(pr, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                return o2.getAge() - o1.getAge();
            }
        });
        pr.forEach(p->{
            System.out.print(p);
        });
    }

The third method: use Stream flow sorting

public static void main(String[] args){



        List<Person> pr=new ArrayList<Person>(){<!-- -->{
            add(new Person(1,"huitao1",32));
            add(new Person(2,"huitao2",40));
            add(new Person(3,"huitao3",28));

        }};
        pr= pr.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());
        pr.forEach(p->{
            System.out.print(p);
        });
    }
    static class Person {

        Integer id;
        String name;
        Integer age;

        public Person(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

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

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

stream() reports a null pointer error if the sorting attribute appears null. Solution

public static void main(String[] args){



        List<Person> pr=new ArrayList<Person>(){<!-- -->{
            add(new Person(1,"huitao1",32));
            add(new Person(2,"huitao2",40));
            add(new Person(3,"huitao3",28));
            add(new Person(4,"huitao3",null));

        }};
        pr= pr.stream().sorted(Comparator.comparing(Person::getAge,Comparator.nullsFirst(Integer::compareTo)).reversed()).collect(Collectors.toList());
        pr.forEach(p->{
            System.out.print(p);
        });
    }
    static class Person {

        Integer id;
        String name;
        Integer age;

        public Person(Integer id, String name, Integer age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

        public Integer getAge() {
            return age;
        }

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

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

Comparator.nullsFirst means to put the null value in the sorted field at the front of the collection. If you want to put the null value at the end of the collection, you can use Comparator.nullsLast.

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