search
HomeJavajavaTutorialHow to use Comparable and Comparator to remove reordering in Java

How to use Comparable and Comparator to remove reordering in Java

May 11, 2023 pm 03:43 PM
javacomparatorcomparable

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);
    }

}
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);
    }
}

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"));
  • 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);
    }

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor