列表对象排序

复制代码
@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);
相关推荐
kakakahahahaha37 分钟前
Windows C盘空间不足的安全清理与迁移流程
windows·电脑·笔记本电脑·软件需求·c盘清理
做咩啊~1 小时前
远程连接提示:身份验证错误,要求的函数不受支持
windows
百事牛科技2 小时前
PPT只读怎么取消?四种情况分别处理
windows·powerpoint
熊明才21 小时前
WSL2 网络突然瘫痪(Network is unreachable / 没有 eth0)最短修复指南(2026年9月20日亲测可用)
linux·windows·wsl2
xbzb1 天前
Windows 启动故障修复知识整理:蓝屏 / 无限重启 / 盘符 X / 无 PE 盘
windows
我命由我123451 天前
Mac 操作系统 - 一些使用记录
运维·windows·学习·系统安全·运维开发·mac·学习方法
kakakahahahaha2 天前
Windows Steam 游戏存档在哪里?定位和恢复排查流程
windows·其他·电脑·笔记本电脑·内容运营·软件需求
Xy-unu2 天前
Windows 开启外接显示器 HDR 后外接显示器无信号、无法扩展模式故障记录
windows
troy1282 天前
Codex 安全盲区:代码漏洞生成实测
windows·python·ci/cd·pycharm·django·github·fastapi
其实防守也摸鱼2 天前
常见安全架构中 Shiro 的认证确认机制解析
运维·服务器·数据库·windows·github