<span style="font-family:KaiTi_GB2312;">背景:对数据库进行批量插入之前,对传入的一列对象按照三个属性进行排序</span>
<span style="font-family:KaiTi_GB2312;">背景:对数据库进行批量插入之前,对传入的一列对象按照三个属性进行排序</span>
步骤:
1.实体类实现Comparable接口,并重写comparaTo方法
package rquest.sort;
/**
*实体类
*/
public class ObjectSortEntity implements Comparable<ObjectSortEntity>{
private String idInstrument;
private String idEvaluation;
private String idScenario;
@Override
public int compareTo(ObjectSortEntity o) {
int i = this.getIdInstrument().compareTo(o.getIdInstrument());//先按照IdInstrument排序
if(i == 0){
//如果IdInstrument相等了,再用idEvaluation进行排序
int j = this.getIdEvaluation().compareTo(o.getIdEvaluation());
if(j==0){
//如果IdEvaluation相等了,再用idScenario进行排序
return this.getIdScenario().compareTo(o.getIdScenario());
}
return j;
}
return i;
}
//此处省略了 get、set 方法
}
</pre></div></div><h3><pre name="code" class="java">import org.junit.Test;
public class test {
@Test
public void testObjectSort(){
List<ObjectSortEntity> list = new ArrayList<ObjectSortEntity>();
ObjectSortEntity b = new ObjectSortEntity();
b.setIdInstrument("111");
b.setIdEvaluation("111");
b.setIdScenario("seca111");
ObjectSortEntity b1 = new ObjectSortEntity();
b1.setIdInstrument("111");
b1.setIdEvaluation("222");
b1.setIdScenario("seca111");
ObjectSortEntity b2 = new ObjectSortEntity();
b2.setIdInstrument("222");
b2.setIdEvaluation("111");
b2.setIdScenario("seca111");
ObjectSortEntity b3 = new ObjectSortEntity();
b3.setIdInstrument("222");
b3.setIdEvaluation("222");
b3.setIdScenario("seca111");
ObjectSortEntity b4 = new ObjectSortEntity();
b4.setIdInstrument("222");
b4.setIdEvaluation("222");
b4.setIdScenario("seca222");
ObjectSortEntity b5 = new ObjectSortEntity();
b5.setIdInstrument("222");
b5.setIdEvaluation("222");
b5.setIdScenario("seca333");
ObjectSortEntity b6 = new ObjectSortEntity();
b6.setIdInstrument("222");
b6.setIdEvaluation("221");
b6.setIdScenario("seca333");
ObjectSortEntity b7 = new ObjectSortEntity();
b7.setIdInstrument("222");
b7.setIdEvaluation("221");
b7.setIdScenario("seca133");
list.add(b5);
list.add(b4);
list.add(b7);
list.add(b);
list.add(b6);
list.add(b3);
list.add(b1);
list.add(b2);
System.out.println("before sort:");
for(ObjectSortEntity objectSortEntity : list){
System.out.println(objectSortEntity.getIdInstrument()+" "+objectSortEntity.getIdEvaluation()+" "+objectSortEntity.getIdScenario());
}
System.out.println("---------------------------");
Collections.sort(list);
System.out.println("after sort:");
for(ObjectSortEntity objectSortEntity : list){
System.out.println(objectSortEntity.getIdInstrument()+" "+objectSortEntity.getIdEvaluation()+" "+objectSortEntity.getIdScenario());
}
}
}
2.测试结果
参考:http://blog.csdn.net/jbgtwang/article/details/6952459