Java collection related learning - the application and difference between the two major interfaces Comparable and Comparator of element sorting

1. Lead to a topic

In the Java language, Comparable and Comparator are both used to sort elements, but there are essential differences between the two.


2.Comparable

The Comparable interface has only one method compareTo. By implementing the Comparable interface and overriding the compareTo method, a certain class can be sorted. It supports the sorting of Collections.sort and Arrays.sort.

The use of Comparable is to implement the Comparable interface in the class of the custom object, and override the compareTo method to implement the custom sorting rule. The parameter p received by the compareTo method is the object to be compared, and the sorting rule is the current object and the one to be compared. Objects are compared and a value of type int is returned. The sorting rule from small to large in positive order is: use the current object value minus the value of the object to be compared; while the sorting rule in reverse order from large to small is just the opposite: the value of the comparison object minus the value of the current object.

The specific implementation code is as follows:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;
import java.util.Map;

/**
 *
 */
class Man implements Comparable<Man> {
    private Integer id;
    private String name;
    private Integer age;

    public Man(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 int compareTo(Man m) {
        return m.getAge() - this.getAge();
    }

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

public class ComparableTest {
    public static void main(String[] args) {
        List<Man> list = new ArrayList<>();
        list.add(new Man(1, "张起灵", 18));
        list.add(new Man(2, "小哥", 22));
        list.add(new Man(3, "闷油瓶", 20));
        Collections.sort(list);
        list.forEach(System.out::println);
    }
}


3.Comparator

The sorting methods of Comparator and Comparable are different. The sorting method of Comparable is compareTo, and the sorting method of Comparator is compare. The specific implementation code is as follows:

import java.util.*;
import java.util.Map;

/**
 *
 */
class Man2 implements Comparable<Man> {
    private String name;
    private Integer age;

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

    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 int compareTo(Man m) {
        return m.getAge() - this.getAge();
    }

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

public class ComparatorTest {
    private static Map<Integer, Man2> sortMap(Map<Integer, Man2> map) {
        //首先拿到 map 的键值对集合
        Set<Map.Entry<Integer, Man2>> entrySet = map.entrySet();
        //将 set 集合转为 List 集合,原因:为了使用工具类的排序方法
        List<Map.Entry<Integer, Man2>> list = new ArrayList<>(entrySet);
        //使用 Collections 集合工具类对 list 进行排序,排序规则使用匿名内部类来实现
        Collections.sort(list, new Comparator<Map.Entry<Integer, Man2>>() {
            @Override
            public int compare(Map.Entry<Integer, Man2> o1, Map.Entry<Integer, Man2> o2) {
                //自定义按照年龄的降序排序
                return o2.getValue().getAge() - o1.getValue().getAge();
            }
        });
        //创建一个新的有序的Map集合
        Map<Integer, Man2> linkedHashMap = new LinkedHashMap<>();
        //将 List 中的数据存储在 LinkedHashMap 中
        list.forEach(m -> {
            linkedHashMap.put(m.getKey(), m.getValue());
        });
        return linkedHashMap;
    }

    public static void main(String[] args) {
        Map<Integer, Man2> map = new HashMap<>();
        map.put(1, new Man2("张起灵", 18));
        map.put(2, new Man2("小哥", 22));
        map.put(3, new Man2("闷油瓶", 20));
        System.out.println("排序之前的map集合为:\n" + map);
        System.out.println("-------------------------------");
        Map<Integer, Man2> sortMap = sortMap(map);
        System.out.println("排序之后的map集合为:\n" + sortMap);
    }
}


4. Compare the two

From the implementation code of the above example, we can see that the use of Comparable must modify the original class, that is, if you want to sort the class, you must implement the Comparable interface and rewrite the compareTo method in that class, so Comparable is more like "Yes" interface for sorting within".

The use of Comparator is not the same, Comparator does not need to modify the original class. That is, in the most extreme case, even if the Person class is provided by a third party, we can still implement the sorting function of the third-party class Person by creating a new custom comparator Comparator. That is to say, the Comparator interface can realize the decoupling from the original class, and realize the sorting function without modifying the original class, so the Comparator can be regarded as an interface that provides sorting "externally".

Comparable and Comparator are both used to implement element sorting. The differences between them are as follows:

  • Comparable means "comparison", and Comparator means "comparator";

  • Comparable implements sorting by overriding the compareTo method, while Comparator implements sorting by overriding the compare method;

  • Comparable must implement the sorting method internally by the custom class, while Comparator is defined externally and implements sorting.

So sum up the difference between the two in one sentence: Comparable can be seen as an "internal" sorting interface, while Comparator is an "external" sorting interface.

Guess you like

Origin blog.csdn.net/weixin_43823808/article/details/124043951