Java原生提供了这一支持,所以我们没必要在开发中再造轮子。这里我们使用的是Comparable接口。
要对比的对象需要实现Comparable接口,并实现一个方法:
compareTo(<T>)
该方法返回1或者-1(最好是互为反数)。
Collections.sort(list);
@Entity
@Table(name = "t_s_dddepart", schema = "")
@SuppressWarnings("serial")
public class DingDingDepart implements java.io.Serializable , Comparable<DingDingDepart> {
/**id*/
private java.lang.Integer id;
/**name*/
@Excel(name="name")
private java.lang.String name;
/**parentid*/
@Excel(name="parentid")
private java.lang.Integer parentid;
/**
*方法: 取得java.lang.Integer
*@return: java.lang.Integer id
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name ="ID",nullable=false,length=13)
public java.lang.Integer getId(){
return this.id;
}
/**
*方法: 设置java.lang.Integer
*@param: java.lang.Integer id
*/
public void setId(java.lang.Integer id){
this.id = id;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String name
*/
@Column(name ="NAME",nullable=true,length=255)
public java.lang.String getName(){
return this.name;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String name
*/
public void setName(java.lang.String name){
this.name = name;
}
/**
*方法: 取得java.lang.Integer
*@return: java.lang.Integer parentid
*/
@Column(name ="PARENTID",nullable=true,length=13)
public java.lang.Integer getParentid(){
return this.parentid;
}
/**
*方法: 设置java.lang.Integer
*@param: java.lang.Integer parentid
*/
public void setParentid(java.lang.Integer parentid){
this.parentid = parentid;
}
@Override
public int compareTo(DingDingDepart o2) {
if( this.getId() == this.getParentid())
return 1;
//注意!!返回值必须是一对相反数,否则无效。jdk1.7以后就是这样。
//else return 0;
//无效
else return -1;
}
public static void main(String[] args) throws Exception{
System.out.println("11111");
DingDingUtil.getAccess_Token();
List<DingDingDepart> list = new ArrayList<DingDingDepart>();
JSONArray departArr = DingDingUtil.getDingDepart();
for (int i = 0; i < departArr.size(); i++) {
DingDingDepart depart = new DingDingDepart();
JSONObject jsonItem = departArr.getJSONObject(i);
depart.setId(jsonItem.getInteger("id"));
depart.setName(jsonItem.getString("name"));
Object pid = jsonItem.get("parentid");
if(pid!=null){
depart.setParentid(jsonItem.getInteger("parentid"));
}else{
depart.setParentid(0);
}
list.add(depart);
}
String a= "";
for(DingDingDepart de: list){
a += de.getId()+ ","+de.getParentid() + "||";
}
System.out.println(a);
Collections.sort(list);
a= "";
for(DingDingDepart de: list){
a += de.getId()+ ","+de.getParentid() + "||";
}
System.out.println(a);
}
}