在某些业务场景下需要根据list列表中对象的字段进行排序。今天就以实例说明:

实体类

public class Product {
    private int discount;
    // 省略getter/setter方法
}

排序测试类

public class TestSortList {

    @Test
    public void test1(){
        List<Product> list = new ArrayList<>(3);
        Product p1 = new Product();
        p1.setDiscount(1);
        list.add(p1);

        Product p2 = new Product();
        p2.setDiscount(2);
        list.add(p2);

        Product p3 = new Product();
        p3.setDiscount(3);
        list.add(p3);

        Collections.sort(list, new Comparator<Product>() {
            @Override
            public int compare(Product o1, Product o2) {
                if(o1.getDiscount() > o2.getDiscount()){
                    return 1;
                } else if(o1.getDiscount() == o2.getDiscount()){
                    return 0;
                } else {
                    return -1;
                }
            }
        });

        for(Product product : list){
            System.out.println(product.getDiscount());
        }

    }
}

打印结果:

1
2
3

这样就完成了一个升序的排序。如果需要降序的排序秩序将o1.getDiscount() > o2.getDiscount()前后调换位置就可以了。

其他

在jdk8中,引入了lambda表达式的写法,因此排序部分代码可简化为:

Collections.sort(list, (o1, o2) -> {
     if(o2.getDiscount() > o1.getDiscount()){
         return 1;
     } else if(o1.getDiscount() == o2.getDiscount()){
         return 0;
     } else {
         return -1;
     }
 });

另外网络上也提供了通用的List排序工具方法,可自行参考学习。

最新文章

  1. JQuery基本知识框架思维导图(上)
  2. 51nod 简单的动态规划
  3. 十年MFC经历认识的Microsoft技术 [转]
  4. Dubbo认识
  5. 【原创】开机出现grub rescue,修复办法
  6. jQuery—一些常见方法(3)【width(),innerWidth(),outerWidth()】
  7. js 中读取JSON的方法探讨
  8. nyoj 325 zb的生日(dfs)
  9. SQL Server索引进阶:第十三级,插入,更新,删除
  10. java.lang.OutOfMemoryError异常解决方法
  11. flex中为控件添加监听器并计算
  12. iPhone / iPad L2TP Client Setup
  13. java的编程习惯影响程序性能
  14. Linux学习笔记之八————vim编辑器常用命令总结
  15. 解决spring-boot启动异常Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
  16. systemd设置静态IP
  17. [0day]微软VS全版本DLL却持漏洞(VS2015 VS2013 VS2012 VS2010 VS2008)
  18. dell support
  19. Django模型层(2)
  20. [BZOJ5338][TJOI2018]xor(可持久化Trie)

热门文章

  1. Docker 网络之端口绑定
  2. yum安装mysql5.6
  3. HDU - 6395 Sequence (分块+快速矩阵幂)
  4. vm安装centos7 Minimal 配置静态ip添加dns: 解决连不上网
  5. ubuntu 16.04安装navicat for mysql
  6. Linux网络性能评估工具iperf 、CHARIOT测试网络吞吐量
  7. cmd命令 启动 和关闭sql服务
  8. H5中的语义化标签
  9. JavaWeb XML
  10. mysql——jdbc驱动下载&amp;连接mysql例子