java将list转树结构(二)
转载于:https://www.csdn.net/tags/MtzaAgwsNDEyMjgtYmxvZwO0O0OO0O0O.html
实体类:
import java.util.List;
public class RegionPojo {
private String code;
private String name;
private String filter; // 父级编码
private List<RegionPojo> children;
getter和setter...
}
核心工具
private static List<RegionPojo> getTree(List<RegionPojo> regions) {
Map<String, RegionPojo> nodeMap = Maps.newHashMap();
List<RegionPojo> rootList = Lists.newArrayList();
for (RegionPojo region : regions) {
nodeMap.put(region.getCode(), region);
String parentId = region.getFilter();
if (parentId == null || parentId == null) {
rootList.add(region);
}
}
for (RegionPojo node : regions) {
String parentId = node.getFilter();
if (parentId == null || parentId == null) {
continue;
}
RegionPojo pnode = nodeMap.get(parentId);
if (pnode == null) {
continue;
}
List<RegionPojo> children = pnode.getChildren();
if (children == null) {
children = Lists.newArrayList();
pnode.setChildren(children);
}
children.add(node);
}
return rootList;
}