@Data
@AllArgsConstructor
public class AnalysisTitleDto {
private String id;
private String pid;
/**
* 表头字段说明
*/
private String label;
/**
* 标题的字段
*/
private String value;
/**
* 子表头
*/
private List<AnalysisTitleDto> children;
public AnalysisTitleDto(String id, String pid) {
this.id = id;
this.pid = pid;
}
public AnalysisTitleDto(String id, String pid, String label, String value) {
this(id, pid);
this.label = label;
this.value = value;
}
// 以0为根节点
final static String rootNode = "0";
// 封装集合为树形结构
private static List<AnalysisTitleDto> buildTree(List<AnalysisTitleDto> analysisTitleDtos) {
Map<String, List<AnalysisTitleDto>> children = analysisTitleDtos.stream().filter(analysisTitleDto -> analysisTitleDto.getPid() != rootNode)
.collect(Collectors.groupingBy(analysisTitleDto -> analysisTitleDto.getPid()));
analysisTitleDtos.forEach(analysisTitleDto -> analysisTitleDto.setChildren(children.get(analysisTitleDto.getId())));
return analysisTitleDtos.stream().filter(analysisTitleDto -> analysisTitleDto.getPid() == rootNode).collect(Collectors.toList());
}
public static List<Map<String, String>> getOneNodeMaps(String menuPath) {
List<String> names = Arrays.asList(menuPath.split(":"));
List<Map<String, String>> list = new ArrayList<>();
if (names.size() >= 2) {
for (int i = 0; i < names.size(); i++) {
if (i+1 < names.size()) {
// 加入根节点
if (i == 0) {
Map<String, String> map = new HashMap<>();
map.put(rootNode, names.get(i));
list.add(map);
}
Map<String, String> map = new HashMap<>();
map.put(names.get(i), names.get(i + 1));
list.add(map);
}
}
}
return list;
}
public static List<Map<String, String>> buildNodeMaps(List<String> paths) {
List<Map<String, String>> allNodeMaps = new ArrayList<>();
paths.stream().forEach(x -> {
List<Map<String, String>> oneNodeMaps = getOneNodeMaps(x);
allNodeMaps.addAll(oneNodeMaps);
});
return allNodeMaps.stream().distinct().collect(Collectors.toList());
}
// 初始化数据集合
private static List<AnalysisTitleDto> getAnalysisTitleDtoList(List<String> paths) {
List<AnalysisTitleDto> list = new ArrayList<AnalysisTitleDto>();
List<Map<String, String>> nodeMaps = buildNodeMaps(paths);
nodeMaps.stream().forEach(x ->{
String pid = (String) x.keySet().toArray()[0];
String id = x.get(pid);
AnalysisTitleDto node = new AnalysisTitleDto(id, pid, id, id);
list.add(node);
});
return list;
}
public static void main(String[] args) {
List<String> paths = new ArrayList<>();
paths.add("A:B:C");
paths.add("A:B:D");
paths.add("A:E");
paths.add("H:F");
paths.add("I:G");
List<AnalysisTitleDto> analysisTitleDtos = buildTree(getAnalysisTitleDtoList(paths));
}
}
java构建树结构
最新推荐文章于 2024-06-06 12:07:21 发布