1)创建城市类和树状结构城市类
//城市类
class City {
private int id;
private String name;
private int upperid;
public City(int id, String name, int upperid) {
this.id = id;
this.name = name;
this.upperid = upperid;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getUpperId() {
return upperid;
}
public void setId(int _id) {
this.id = _id;
}
public void setName(String _name) {
this.name = _name;
}
public void setUpperId(int _upperid) {
this.upperid = _upperid;
}
}
//树状结构城市类
class TreeNode extends City {
private List<TreeNode> children = new ArrayList<TreeNode>();
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> _children) {
this.children = _children;
}
public TreeNode(int id, String name, int upperid) {
super(id, name,upperid);
}
}
2)初始化数据,创建将列表集合转化成树集合
// 获取城市列表
private List<City> GetList() {
List<City> list = new ArrayList<>();
list.add(new City(1, "浙江", 0));
list.add(new City(2, "江苏", 0));
list.add(new City(3, "福建", 0));
list.add(new City(11, "杭州", 1));
list.add(new City(12, "嘉兴", 1));
list.add(new City(21, "苏州", 2));
list.add(new City(22, "无锡", 2));
list.add(new City(31, "福州", 3));
list.add(new City(32, "厦门", 3));
list.add(new City(111, "萧山", 11));
list.add(new City(112, "临安", 11));
list.add(new City(121, "嘉善", 12));
list.add(new City(122, "桐乡", 12));
list.add(new City(211, "吴江", 21));
list.add(new City(212, "常熟", 21));
return list;
}
// 获取城市树状结构
private List<TreeNode> GetTree(int upperId, List<City> list) {
return list.stream()
.filter(a -> a.getUpperId() == upperId)
.map(child -> {
TreeNode node = new TreeNode(
child.getId(),
child.getName(),
child.getUpperId()
);
List<TreeNode> myChildren = GetTree(child.getId(), list);
node.setChildren(myChildren);
return node;
})
.collect(Collectors.toList());
}
3)调用
List<City> list = GetList();
List<TreeNode> tree = GetTree(0, list);