你知道的越多,你不知道的越多
点赞再看,养成习惯
如果您有疑问或者见解,欢迎指教:
企鹅:869192208
最近遇到一个地区数据需要转换成树的需求,研究了一种新方法,不使用传统递归的方式,而是使用 stream 流的方式构建树。
import lombok.Data;
import java.util.List;
/**
* <h2> </h2>
*
* @author xymy
* @date 2023/12/21 17:17
*/
@Data
public class TsModel {
private String id;
private String name;
private String pid;
private List<TsModel> childs;
}
public static void main(String[] args) {
String str = "[\n" +
" {\"id\":\"1\",\"name\":\"张三\",\"pid\":\"\"},\n" +
" {\"id\":\"2\",\"name\":\"张三2\",\"pid\":\"\"},\n" +
" {\"id\":\"3\",\"name\":\"张三3\",\"pid\":\"\"},\n" +
" {\"id\":\"4\",\"name\":\"张三4\",\"pid\":\"\"},\n" +
" {\"id\":\"33\",\"name\":\"张三33\",\"pid\":\"3\"},\n" +
" {\"id\":\"330\",\"name\":\"张三330\",\"pid\":\"3\"},\n" +
" {\"id\":\"3301\",\"name\":\"张三330\",\"pid\":\"330\"},\n" +
" {\"id\":\"41\",\"name\":\"张三41\",\"pid\":\"4\"}\n" +
"]";
List<TsModel> tsModels = JSONArray.parseArray(str, TsModel.class);
Map<String, List<TsModel>> pModels = tsModels.stream().collect(Collectors.groupingBy(ts -> StringUtils.isBlank(ts.getPid()) ? "" : ts.getPid()));
List<TsModel> childTs = new ArrayList<>();
for (TsModel tsModel : tsModels) {
String id = tsModel.getId();
List<TsModel> childModel = pModels.get(id);
if (CollectionUtils.isNotEmpty(childModel)) {
tsModel.setChilds(childModel);
childTs.addAll(childModel);
}
}
Set<String> childSeqs = childTs.stream().map(t -> t.getId()).collect(Collectors.toSet());
List<TsModel> newTree = tsModels.stream().filter(tsm -> !childSeqs.contains(tsm.getId())).collect(Collectors.toList());
System.out.println(JSON.toJSONString(newTree));
}
打印结果:
[
{
"id": "1",
"name": "张三",
"pid": ""
},
{
"id": "2",
"name": "张三2",
"pid": ""
},
{
"childs": [
{
"id": "33",
"name": "张三33",
"pid": "3"
},
{
"childs": [
{
"id": "3301",
"name": "张三330",
"pid": "330"
}
],
"id": "330",
"name": "张三330",
"pid": "3"
}
],
"id": "3",
"name": "张三3",
"pid": ""
},
{
"childs": [
{
"id": "41",
"name": "张三41",
"pid": "4"
}
],
"id": "4",
"name": "张三4",
"pid": ""
}
]
至此,就实现了列表转成树的逻辑。