比如我有一个javabean:
//部门类
public class Territory{
private int id;
private String territoryName;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setTerritoryName(String territoryName){
this.territoryName = territoryName;
}
public String getTerritoryName(){
return territoryName;
}
}
一个业务类:
public class DataMigrationDao{
Territory t1 = new Territory();
t1.setId(5);
t1.setTerritoryName("t1");
Territory t2 = new Territory();
t2.setId(1);
t2.setTerritoryName("t2");
Territory t3 = new Territory();
t2.setId(3);
t2.setTerritoryName("t3");
List<Territory> list = new ArrayList<Territory>();
list.add(t1);
list.add(t2);
list.add(t3);
//现在对list集合进行升序排序
Collections.sort(list, new CompareUnit());
.....
//将重新排序的list进行持久化等其他操作
}
//内部类
//这是升序,如果想降序,就把if(..>..){return -1} if(..<..){return 1} return 0
class CompareUnit implements Comparator<Territory>{
@Override
public int compare(Territory t1, Territory t2) {
if(t1.getId()<t2.getId()){
return -1;
}
if(t1.getId()>t2.getId()){
return 1;
}
return 0;
}
}
转载于:https://my.oschina.net/WvTKXOU/blog/401228