列表对象排序

复制代码
@Data
class Product implements Comparator<Product>{
    String name;
    int popularity;
    int salesVolume;
    public String toString() {
        return String.format(java.util.Locale.ROOT, "[\"%s\", %d, %d]", name, popularity, salesVolume);
    }

    @Override
    public int compare(Product o1, Product o2) {
        if (o1.popularity != o2.popularity) {
            return o2.popularity - o1.popularity;
        } else if (o1.popularity == o2.popularity &&
            o1.salesVolume != o2.salesVolume) {
            return o2.salesVolume - o1.salesVolume;
        } else if (o1.popularity == o2.popularity &&
            o1.salesVolume == o2.salesVolume) {
            return o1.name.compareTo(o2.name);
        }
        return 0;
    }
}
public class test
{
    public static void main(String[] args) {
        Product product1 = new Product();
        product1.setName("product1");
        product1.setPopularity(10);
        product1.setSalesVolume(100);
        Product product2=new Product();
        product2.setName("product2");
        product2.setPopularity(20);
        product2.setSalesVolume(200);
        Product product3=new Product();
        product3.setName("product3");
        product3.setPopularity(20);
        product3.setSalesVolume(150);
        List<Product> list=new ArrayList<>();
        list.add(product1);
        list.add(product2);
        list.add(product3);
        System.out.println(list);
        list.sort(new Product());
        System.out.println(list);
    }
}

内部类写法

复制代码
Collections.sort(list, new Comparator<Product>() {
    @Override
    public int compare(Product o1, Product o2) {
        if (o1.popularity != o2.popularity) {
            return o2.popularity - o1.popularity;
        } else if (o1.popularity == o2.popularity &&
            o1.salesVolume != o2.salesVolume) {
            return o2.salesVolume - o1.salesVolume;
        } else if (o1.popularity == o2.popularity &&
            o1.salesVolume == o2.salesVolume) {
            return o1.name.compareTo(o2.name);
        }
        return 0;
    }
});
System.out.println(list);
相关推荐
问道飞鱼1 小时前
【Tauri框架学习】Windows 11 环境下 Tauri 开发环境安装与问题解决手册
windows·学习·tauri·开发环境
xiaoliuliu123452 小时前
Autodesk官方卸载工具使用教程(Windows版,含解压+管理员运行+批量卸载)
windows
johnrui4 小时前
集合与树形结构
开发语言·windows
柯儿的天空5 小时前
【OpenClaw 全面解析:从零到精通】第 006 篇:OpenClaw 在 Windows/WSL2 上的安装与部署实战
人工智能·windows·语言模型·chatgpt·ai作画
阿昭L7 小时前
说说Windows进程的令牌(token)
windows·系统安全·token
包饭厅咸鱼9 小时前
小龙虾openclaw----Windows+Wsl+Docker 安装openclaw 并接入飞书
windows·docker·openclaw·小龙虾
※※冰馨※※9 小时前
【QT】TortoiseGit配 SSH 克隆 Codeup
开发语言·c++·windows
今夕资源网10 小时前
坚果手机直连Windows,打开软件实现键鼠操作TNT系统 视频教程+所需软件(今夕存档)
windows·智能手机·tnt·smartisan·smartisan tnt·锤子系统·坚果手机
alphaTao11 小时前
LeetCode 每日一题 2026/3/16-2026/3/22
linux·windows·leetcode
阿昭L11 小时前
说说VirtualAlloc的第三个参数
windows