地区表
CREATE TABLE `zone` ( `id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `parent_id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
实体类
public class Zone {
private String id;
private String name;
private String parentId;
private List children;
}
工具类
public class ZoneUtils {
public static List buildTree2(List zoneList) {
List result = new ArrayList<>();
for (Zone zone : zoneList) {
if (zone.parentId.equals("0")) {
result.add(zone);
}
for (Zone child : zoneList) {
if (child.parentId.equals(zone.id)) {
zone.addChildren(child);
}
}
}
return result;
}
public static List buildTree3(List zoneList) {
Map> zoneByParentIdMap = new HashMap<>();
zoneList.forEach(zone -> {
List children = zoneByParentIdMap.getOrDefault(zone.parentId, new ArrayList<>());
children.add(zone);
zoneByParentIdMap.put(zone.parentId, children);
});
zoneList.forEach(zone -> zone.children = zoneByParentIdMap.get(zone.id));
return zoneList.stream()
.filter(v -> v.parentId.equals("0"))
.collect(Collectors.toList());
}
public static List buildTree3_01(List zoneList) {
Map> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
zoneList.forEach(zone -> zone.children = zoneByParentIdMap.get(zone.id));
return zoneList.stream().filter(v -> v.parentId.equals("0")).collect(Collectors.toList());
}
}



