惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
V
Vulnerabilities – Threatpost
MongoDB | Blog
MongoDB | Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Proofpoint News Feed
Know Your Adversary
Know Your Adversary
aimingoo的专栏
aimingoo的专栏
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
T
Tor Project blog
A
Arctic Wolf
L
LangChain Blog
L
LINUX DO - 热门话题
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
Stack Overflow Blog
Stack Overflow Blog
I
Intezer
爱范儿
爱范儿
P
Palo Alto Networks Blog
WordPress大学
WordPress大学
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
G
GRAHAM CLULEY
S
Securelist
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Cisco Talos Blog
Cisco Talos Blog
Security Latest
Security Latest
Martin Fowler
Martin Fowler
AWS News Blog
AWS News Blog
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
酷 壳 – CoolShell
酷 壳 – CoolShell
Recorded Future
Recorded Future
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
Apple Machine Learning Research
Apple Machine Learning Research
V2EX - 技术
V2EX - 技术
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
LINUX DO - 最新话题
博客园 - Franky
P
Privacy & Cybersecurity Law Blog
Simon Willison's Weblog
Simon Willison's Weblog
W
WeLiveSecurity
Cyberwarzone
Cyberwarzone
The Hacker News
The Hacker News
A
About on SuperTechFans

博客园 - 有点懒惰的大青年

用一个实际业务场景演示ON和WHERE的正确使用方式 idea中查看源码 异或运算 使用Hutool对时间的花式操作 合并K个升序列表 枚举类的设计模式 spring boot中使用RedissonClient实现分布式锁 idea同时启动application,启用不同端口 @PostConstruct用法 ApplicationContext 事件发布与监听机制详解 java自带命令jps介绍 关于maven中标签的说明 mysql的跨库查询 linux命令ll显示结果的含义 Files类的使用 java环境变量设置 java值传递和引用传递 kafka的集群与可靠性 kafka的消费全流程 关于kafka 达梦数据库执行计划介绍 关于MQ 用位运算实现加减乘除(3)
比较器
有点懒惰的大青年 · 2026-03-19 · via 博客园 - 有点懒惰的大青年

一、自定义比较器实现任意一个javaBean之间的比较

package com.cy.class06;

import java.util.ArrayList;
import java.util.Arrays;

public class ShowComparator {

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void printStudents(Student[] students) {
        for (int i = 0; i < students.length; i++) {
            System.out.println(students[i].name + ", " + students[i].id + ", " + students[i].age);
        }
    }

    public static void main(String[] args) {
        int[] arr = { 8, 1, 4, 1, 6, 8, 4, 1, 5, 8, 2, 3, 0 };
        printArray(arr);
        Arrays.sort(arr);
        printArray(arr);

        Student s1 = new Student("张三", 5, 27);
        Student s2 = new Student("李四", 1, 17);
        Student s3 = new Student("王五", 4, 29);
        Student s4 = new Student("赵六", 3, 9);
        Student s5 = new Student("左七", 2, 34);

        Student[] students = { s1, s2, s3, s4, s5 };
        printStudents(students);
        System.out.println("=======");
        Arrays.sort(students, new IdComparator());
        printStudents(students);
        System.out.println("=======");

        ArrayList<Student> arrList = new ArrayList<>();
        arrList.add(s1);
        arrList.add(s2);
        arrList.add(s3);
        arrList.add(s4);
        arrList.add(s5);
        for (Student s : arrList) {
            System.out.println(s.name + ", " + s.id + ", " + s.age);
        }
        System.out.println("=======");
        arrList.sort(new IdComparator());
        for (Student s : arrList) {
            System.out.println(s.name + ", " + s.id + ", " + s.age);
        }
    }
}

IdComparator比较器:

package com.cy.class06;

import java.util.Comparator;

/**
 * id比较器,谁id大,谁放前
 */
public class IdComparator implements Comparator<Student> {

    // 如果返回负数,认为第一个参数应该排在前面
    // 如果返回正数,认为第二个参数应该排在前面
    // 如果返回0,认为谁放前面无所谓
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.id < o2.id) {
            return 1;
        } else if (o2.id < o1.id) {
            return -1;
        } else {
            return 0;
        }
    }
}

Student类:

package com.cy.class06;

public class Student {
    public String name;
    public int id;
    public int age;

    public Student(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }
}

二、jdk自带的有序队列,小根堆,相关使用

PriorityQueue的使用介绍,如何实现大根堆,还有哪些跟有序有关的结构?treeMap,treeSet都是。
另外String字符串是按照字典序来排序的。

package com.cy.class06;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.TreeSet;

public class ShowComparator2 {

    public static class MyComparator implements Comparator<Integer> {

        /**
         * 负,第一个参数放前
         * 正,第二个参数放前
         * 0,无所谓,表示相等
         */
        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 < o2) {
                return 1;
            } else if (o1 > o2) {
                return -1;
            } else {
                return 0;
            }
        }
    }

    public static void main(String[] args) {
        test4();
    }

    /**
     * PriorityQueue: 小根堆,优先级队列,从小到大排好序的,而且代价非常的好,logN级别
     * 这里默认是基础类型,默认是小根堆,但是我现在希望是大根堆,动态加入数字,最大的在前面,弹出一个之后,次大的顶上来,怎么做?
     * 可以自己实现比较器来完成。
     */
    public static void test1() {
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        heap.add(6);
        heap.add(2);
        heap.add(3);
        heap.add(1);
        heap.add(7);
        System.out.println(heap.peek());
        heap.add(0);
        System.out.println(heap.peek());

        while(!heap.isEmpty()) {
            System.out.println(heap.poll());
        }
    }

    /**
     * 大根堆,传入比较器,告诉它不用默认的比较器。这个结构出来之后,大数在前
     */
    public static void test2() {
        PriorityQueue<Integer> heap = new PriorityQueue<>(new MyComparator());
        heap.add(6);
        heap.add(2);
        heap.add(3);
        heap.add(1);
        heap.add(7);
        while(!heap.isEmpty()) {
            System.out.println(heap.poll());
        }
    }

    /**
     * 传入自定义的javaBean,内部按照IdComparator的规则排序
     * PriorityQueue,是跟有序有关的结构,都可以这么干
     * 还有哪些跟有序有关的结构?treeMap,treeSet
     *
     * treeSet,底层是红黑树
     *
     * 比较器是干嘛的?系统自带的排序或者系统自带的结构,如果它天然要求有序的东西,只要自己定义好怎么比大小,直接可以用系统提供的来。
     */
    public static void test3() {
        PriorityQueue<Student> heap = new PriorityQueue<>(new IdComparator());
        Student s1 = new Student("张三", 5, 27);
        Student s2 = new Student("李四", 1, 17);
        Student s3 = new Student("王五", 4, 29);
        Student s4 = new Student("赵六", 3, 9);
        Student s5 = new Student("左七", 2, 34);
        heap.add(s1);
        heap.add(s2);
        heap.add(s3);
        heap.add(s4);
        heap.add(s5);
        while(!heap.isEmpty()) {
            Student s = heap.poll();
            System.out.println(s.name + ", " + s.id + ", " + s.age);
        }

        /**
         * TreeSet里面的对象必须是可以比较的,在这个有序的结构中,它就会按照你给定的比较器这个比较预期去排序。
         */
        TreeSet<Student> treeSet = new TreeSet<>(new IdComparator());
    }

    /**
     * String字符串是按照字典序来排序的,所有语言都一样
     * 1) 如果比较的两个字符串是等长的,直接按照数字来进行比较。abc 和 bck,比较第1个字符,a的ascii码小于b的ascii码,所以abc < bck
     * 2) 对于长度不一样的,比如abc 和 b比较,短的补成和长的一样长,拿最低的ascii码来补,补完之后两个再比。补完序后:abc < b00
     */
    public static void test4() {
        String str1 = "abc";
        String str2 = "abd";
        System.out.println(str1.compareTo(str2));       // -1
    }
}