List列表按照对象进行排序
2024-08-27 00:16:12
在某些业务场景下需要根据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排序工具方法,可自行参考学习。
最新文章
- JQuery基本知识框架思维导图(上)
- 51nod 简单的动态规划
- 十年MFC经历认识的Microsoft技术 [转]
- Dubbo认识
- 【原创】开机出现grub rescue,修复办法
- jQuery—一些常见方法(3)【width(),innerWidth(),outerWidth()】
- js 中读取JSON的方法探讨
- nyoj 325 zb的生日(dfs)
- SQL Server索引进阶:第十三级,插入,更新,删除
- java.lang.OutOfMemoryError异常解决方法
- flex中为控件添加监听器并计算
- iPhone / iPad L2TP Client Setup
- java的编程习惯影响程序性能
- Linux学习笔记之八————vim编辑器常用命令总结
- 解决spring-boot启动异常Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
- systemd设置静态IP
- [0day]微软VS全版本DLL却持漏洞(VS2015 VS2013 VS2012 VS2010 VS2008)
- dell support
- Django模型层(2)
- [BZOJ5338][TJOI2018]xor(可持久化Trie)