在某些业务场景下需要根据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排序工具方法,可自行参考学习。