列表对象排序

复制代码
@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);
相关推荐
埃博拉酱2 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21883 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号33 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
tryCbest3 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅3 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
百事牛科技3 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~3 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑
一个假的前端男3 天前
[特殊字符] Flutter 安装完整指南 Windows—— 2026最新版
windows·flutter
倚肆3 天前
在 Windows Docker 中安装并配置 Nginx (映射 Windows 端口与路径)
windows·nginx·docker
破无差3 天前
拯救你的C盘
windows