Home > Java > javaTutorial > How to use Comparable and Comparator to remove reordering in Java

How to use Comparable and Comparator to remove reordering in Java

王林
Release: 2023-05-11 15:43:06
forward
961 people have browsed it

1. Sorting and deduplication

In daily work, there are always some scenarios that require some filtering of the result set. For example, the result set obtained after interacting with a third party needs to be sorted and deduplicated again. In this case, the result set will be deduplicated according to a certain field, or sorted by a certain field.

In Java, when removing duplicates, we can easily think of the characteristics of Set (no order and no duplication), and TreeSet (ordered and no duplication) can also specify the rules for deduplication (generally after deduplication) is the result set in ascending order).

When it comes to sorting, we can easily think of various sorting algorithms, but Java already provides sorting functions, such as the sort() method in collections, and you can also specify the sorting fields and ascending and descending order.

Let me say one more thing here, the characteristics of Set (no order and no duplication):

  • Disorder: disorder is not randomness, Because the element placed in the set will be placed according to the hash value of the element to determine the location

  • No weight: When adding an element, it will be judged according to the equals() of the element. false will only be added when it thinks the two elements are not equal.

2. The use of Comparable and Comparator

public class CompareTest {

    public static void main(String[] args) {
        // 例如:从第三方返回的结果集
        // 根据id去重,根据createTime降序排列
        String result = "["
                + "{ \"id\": 1, \"createTime\": \"2022-12-21 13:23:59\"}"
                + "{ \"id\": 2, \"createTime\": \"2022-11-11 12:43:01\"}"
                + "{ \"id\": 1, \"createTime\": \"2022-12-21 11:20:50\"}"
                + "{ \"id\": 3, \"createTime\": \"2023-01-01 14:30:00\"}"
                + "]";
        JSONArray examList = JSONArray.parseArray(result);
        System.out.println("初始数据集:" + examList);

        // 去重,利用set特性
        Comparator<JSONObject> comparator = (a, b) -> Integer.compare(a.getIntValue("id"), b.getIntValue("id"));
        Set<JSONObject> set = new TreeSet<>(comparator);
        examList.forEach(jo -> set.add((JSONObject) jo));
        // 此时的结果是,根据id去重,并且是升序的结果(自然排序)
        System.out.println("去重结果:" + set);

        // 此处为了,方便演示Comparable接口的作用,故把JSON映射成实体类,进行实现接口排序,其实sorted也可以使用Comparator排序
        List<ExamInfo> collect = set.stream()
                .map(jo -> JSONObject.toJavaObject(jo, ExamInfo.class))
                .sorted()
                .collect(Collectors.toList());
        System.out.println("指定排序结果:" + collect);
    }

}
Copy after login
public class ExamInfo implements Comparable<ExamInfo> {

    private int id;
    private String createTime;

    public int getId() {
        return id;
    }

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

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    @Override
    public String toString() {
        return "ExamInfo{" +
                "id=" + id +
                ", createTime=&#39;" + createTime + &#39;\&#39;&#39; +
                &#39;}&#39;;
    }

    @Override
    public int compareTo(ExamInfo o) {
        // 降序
        return o.getCreateTime().compareTo(this.createTime);
    }
}
Copy after login

How to use Comparable and Comparator to remove reordering in Java

Regarding the issue of ascending and descending sorting, the return values ​​of the comparison methods in Comparable and Comparator are exchanged if they are greater than 0.

So when the order of parameters is a, b:

  • If a>b, that is, a-b>0, because the order is a, b, after exchange, b is in front, a is in the back, the sorting order is ascending order , which is natural sorting;

 // 升序
 Comparator<JSONObject> comparator = (a, b) -> Integer.compare(a.getIntValue("id"), b.getIntValue("id"));
Copy after login
  • If b>a, that is, b-a>0, because the order is a, b. After the exchange, b is in front, a is in the back, and the sorting order is descending order.

 	@Override
 	public int compareTo(ExamInfo o) {
        // 降序
        return o.getCreateTime().compareTo(this.createTime);
    }
Copy after login

3. Difference

##ComparableComparatorThe package to which java.langjava.util is Functional interface is is comparison method int compareTo(T o) int compare(T o1, T o2)Usage scenarioThe compared object can be modified by yourselfThe compared object cannot be modified by yourself. Or the object implements the Comparable interface, but the comparison rules do not apply

The above is the detailed content of How to use Comparable and Comparator to remove reordering in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template