How to use Comparable and Comparator to remove reordering in Java
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='" + createTime + '\'' + '}'; } @Override public int compareTo(ExamInfo o) { // 降序 return o.getCreateTime().compareTo(this.createTime); } }
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
Comparator | ||
---|---|---|
java.lang | java.util | |
is | is | |
int compareTo(T o) | int compare(T o1, T o2) | |
The compared object can be modified by yourself | The 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!

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

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

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

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]

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor