需求:
根據身份的上下層級關係進行排序:
1、沒有上級的排在前。
2、有上級的,按升序排列,即下級在前,上級在後。
實現:
建一個簡單的身份類
/**
* @author chenqi
* @version V1.0
* @ClassName: identity
* @Description: 身份類
* @Date 2019/10/18 15:02
*/
@Data
public class identity implements Serializable {
private static final long serialVersionUID = 3403724365164506666L;
/** 身份id */
private Long id;
/** 身份上級id */
private Long parentId;
}
推薦使用lombok,可以省略get、set方法代碼
實現代碼:
public static void main(String[] args) {
List<identity> list = new ArrayList<>();
//i1的上級是i4
identity i1 = new identity();
i1.setId(1L);
i1.setParentId(4L);
//i2沒有上級
identity i2 = new identity();
i2.setId(2L);
//i3的上級是i1
identity i3 = new identity();
i3.setId(3L);
i3.setParentId(1L);
//i4的上級是0 則i4是最高級
identity i4 = new identity();
i4.setId(4L);
i4.setParentId(0L);
//i5的上級是i4
identity i5 = new identity();
i5.setId(5L);
i5.setParentId(4L);
list.add(i1);
list.add(i2);
list.add(i3);
list.add(i4);
list.add(i5);
System.out.println("===排序前===");
list.stream().forEach(item -> {
System.out.println(item.getId());
});
Collections.sort(list, new Comparator<identity>() {
@Override
public int compare(identity i1, identity i2) {
if(i1 == i2){
return 0;
}else if(CheckUtils.objCheckNull(i1.getParentId())){
return -1;//上級id爲空的排在前
}else if(i1.getParentId().intValue() == i2.getId().intValue()) {
return -1;//i1 的上級是 i2 則往前排
}else{
return 1;
}
}
});
System.out.println("===排序後===");
list.stream().forEach(item -> {
System.out.println(item.getId());
});
}
運行結果:
思路:
通過重寫Comparator類的compare()方法進行自定義排序規則,該方法接收兩個排序對象入參,如:i1和i2,返回int值。即當返回-1時,則i1在前,i2在後,反之,當返回1時,i1在後,i2在前。
至此,完成了對有上下關係層級的數據進行自定義規則排序。
如果該文章有幫助到您,就留言點個贊吧!您的支持與肯定是我持續更新最大的動力。