javabean:Description类
private String code;
private int slevel;
private List<Description> children = new ArrayList<Description>();
数据:
code sLevel
001 1
002 1
001001 2
002001 2
001002 2
001001001 3
001001002 3
001002001 3
002001001 3
002001002 3
002001003 3
001001001001 4
003 1
003001 2
003001001 3
003002 2
现在这个code能是无限以3位进行递增的层级码,怎么可以做到001是主,能把001001放到它的chileren里,把001001001、001001002放到001001的children里,这样用List 展示出来
------解决思路----------------------
我在javabean里面加了个Description parent 属性 代表上级对象 好取值
思路就是先把code按层级排好序 然后循环获取当前对象与下一个对象的关系 3种情况 分别是level大于等于小于
datas = initData();
// 排序
Collections.sort(datas, new Comparator<Description>() {
@Override
public int compare(Description o1, Description o2) {
return o1.getCode().compareTo(o2.getCode());
}
});
for (Description data : datas) {
System.out.println(data);
}
List<Description> levelData = new ArrayList<Description>();
int nextIndex = 0;
for (Description description : datas) {
nextIndex++;
if (description.getSlevel() == 1)
levelData.add(description);
if (nextIndex >= datas.size())
break;
int currLevel = description.getSlevel(),
nextLevel = datas.get(nextIndex).getSlevel();
if (currLevel == nextLevel) {
if (description.getSlevel() > 1) {
datas.get(nextIndex).setParent(description.getParent());
description.getParent().getChildren().add(datas.get(nextIndex));
}
} else if (currLevel < nextLevel) {
datas.get(nextIndex).setParent(description);
description.getChildren().add(datas.get(nextIndex));
} else if (currLevel > nextLevel){
if (nextLevel > 1) {
datas.get(nextIndex).setParent(description.getParent().getParent());
description.getParent().getParent().getChildren().add(datas.get(nextIndex));
}
}
}
感觉好繁琐 应该会有更好的方法