列表对象排序

复制代码
@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 天前
Windows JDK11 下载安装教程,适合新手
java·windows·jdk11 下载安装·jdk11 下载教程
编码者卢布1 天前
【App Service】Java应用上传文件功能部署在App Service Windows上报错 413 Payload Too Large
java·开发语言·windows
多来哈米1 天前
openclaw在Windows部署
windows·openclaw
视觉AI1 天前
【踩坑实录】Windows ICS 共享网络下,国产化盒子 SSH 连接异常的完整分析
网络·windows·ssh
qq_246646191 天前
openclaw快速安装-windows版
windows·stm32·单片机
sonrisa_1 天前
Python同一类不同方法中变量值的传递
开发语言·windows·python
玖釉-1 天前
探索连续细节层次(Continuous LOD):深入解析 NVIDIA 的 nv_cluster_lod_builder
c++·windows·图形渲染
MyY_DO1 天前
第九课ida与花指令
windows·od
多多*1 天前
Mysql数据库相关 事务 MVCC与锁的爱恨情仇 锁的层次架构 InnoDB锁分析
java·数据库·windows·sql·oracle·面试·哈希算法
LateFrames1 天前
“蚯蚓涌动” 的屏保: DirectX 12 + ComputeSharp + Win32
windows·ui·gpu算力