public static void main(String[] args) {
List<Zone> zones = listWithTree();
for (Zone zone : zones) {
System.out.println(zone.getName());
}
}
public static List<Zone> listWithTree() {
// 1、查出所有分类
List<Zone> zoneList = new ArrayList<>();
zoneList.add(new Zone(1,"成都",0));
zoneList.add(new Zone(2,"南昌",0));
zoneList.add(new Zone(3,"四川",0));
zoneList.add(new Zone(4,"绵阳",3));
zoneList.add(new Zone(5,"天津",3));
zoneList.add(new Zone(6,"德阳",4));
zoneList.add(new Zone(7,"西充",1));
zoneList.add(new Zone(8,"重庆",7));
// 组装成父子的树形结构
ArrayList<Zone> result = new ArrayList<>();
zoneList.stream().filter(m1 ->
m1.getParentId() == 0
).peek(menu -> {
result.addAll(getChildren(menu, zoneList, 0));
}).collect(Collectors.toList());
return result;
}
private static List<Zone> getChildren(Zone parent, List<Zone> all, int count){
System.out.println("id===="+parent.getId()+"===count===="+count);
List<Zone> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(" ");
}
parent.setName(sb.append(parent.getName()).toString());
list.add(parent);
count++;
int finalCount = count;
Optional.ofNullable(all).orElse(new ArrayList<>())
.stream()
.filter(item -> parent.getId() == item.getParentId())
.forEach(item -> {
List<Zone> subList;
if (item.getParentId() == 0){
subList = getChildren(item, all, 0);
}else{
subList = getChildren(item, all, finalCount);
}
list.addAll(subList);
});
return list;
}
Zone实体
public class Zone {
int id;
String name;
int parentId;
List<Zone> children;
public Zone(int id, String name, int parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public void addChildren(Zone zone){
if(children == null) {
children = new ArrayList<>();
}
children.add(zone);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public List<Zone> getChildren() {
return children;
}
public void setChildren(List<Zone> children) {
this.children = children;
}
}