列表对象排序

复制代码
@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);
相关推荐
jack1868913 小时前
Devin 智能软件工程师实战应用指南
windows
Hello_Pyhx15 小时前
WinDirStat 2.9.3:从目录扫描到可复查的占用报表
windows·mac·垃圾清理
jun_bai16 小时前
使用Aspose实现word文档合并,内容替换
windows·c#·word
mklpo14718 小时前
为不支持sse4.2命令集的老旧设备制作Win11 26H2系统镜像,2026-10-11。
运维·windows·python
Vex2une18 小时前
PowerShell 发展史:从命令行外壳到跨平台自动化引擎
windows·自动化·azure·powershell·vs code·脚本语言·dsc
富洋金锐19 小时前
windows-winmtr与pathping命令-网络丢包排查
网络·windows
xuxigifxfh19 小时前
牛客:BISHI2 【模板】栈的操作
java·开发语言·windows·算法
imperialeast1 天前
WinAXP 2.4.0.828正式版
windows
周小董1 天前
[1369]Windows上安装PostgreSQL
数据库·windows·postgresql
doujiaozh1 天前
Win7 复活记:用 3 个补丁让 13 年前的老电脑跑通 Kimi API
windows