如何根据实体类中的一个或者多个字段进行进行排序:
//测试用实体类下面是干货:
public class test{
private String name;
private Integer orderOne;
private Integer orderTwo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getOrderOne() {
return orderOne;
}
public void setOrderOne(Integer orderOne) {
this.orderOne = orderOne;
}
public Integer getOrderTwo() {
return orderTwo;
}
public void setOrderTwo(Integer orderTwo) {
this.orderTwo = orderTwo;
}
public test(String name, Integer orderOne, Integer orderTwo) {
this.name = name;
this.orderOne = orderOne;
this.orderTwo = orderTwo;
}
}
//需要导入的包
import java.util.Collections;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
@Test
public void testOrderBeansList(){
//测试用集合
List<test> list = new ArrayList<test>();
//添加十个测试数据
for(int i = 0;i<10;i++){
Random random=new Random();// 定义随机类
int num1=random.nextInt(10);// 返回[0,10)集合中的随机整数,注意不包括10
int num2=random.nextInt(10);// 返回[0,10)集合中的随机整数,注意不包括10
test t = new test("name"+num1,num1,num2);
list.add(t);
}
try {
//根据集合中的某个字段,对集合排序__特别适用于从mongoDB中从多层嵌套取出的数据,方便对其排序
ComparatorChain chain = new ComparatorChain();
chain.addComparator(new BeanComparator("orderOne"), false);//true,false降序升序
chain.addComparator(new BeanComparator("orderTwo"), true);//true,false降序升序
Collections.sort(list, chain);//List<T> 或者是其他的集合
} catch (Exception e) {
e.printStackTrace();
}
}
结果如下:
/********************************以往使用的感觉比较冗余的写法****************************************/
try {
Comparator mycmp1 = ComparableComparator.getInstance ();
mycmp1 = ComparatorUtils. reversedComparator(mycmp1); //倒序
Comparator mycmp2 = ComparableComparator.getInstance ();
mycmp2 = ComparatorUtils. nullHighComparator(mycmp2); //允许null,正序递增排列
// 声明要排序的对象的属性,并指明所使用的排序规则,如果不指明,则用默认排序
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add( new BeanComparator("orderOne" , mycmp1)); //主排序(第一排序)
sortFields.add( new BeanComparator("orderTwo" , mycmp2)); //次排序(第二排序)
// 创建一个排序链
ComparatorChain multiSort = new ComparatorChain(sortFields);
// 开始真正的排序,按照先主,后副的规则
Collections.sort (list , multiSort);
} catch (Exception e) {
e.printStackTrace();
}
/********************************以往使用的感觉比较冗余的写法****************************************/
结果如下: