首页 > 编程语言 >史上最简单的JAVA集合(List)转树(Tree)方法

史上最简单的JAVA集合(List)转树(Tree)方法

时间:2022-10-20 10:07:56浏览次数:52  
标签:JAVA pIdToChildrenListMap stream List Tree DemoData sources entry

/**
* 将数据转换为树型结构
*
* @param sources sources
* @return {@link List<DemoData>}
*/
public static List<DemoData> transToTree(List<DemoData> sources) {
if (CollectionUtils.isEmpty(sources)) {
return Collections.emptyList();
}
Map<Integer, DemoData> sourceMap = sources.stream().collect(Collectors.toMap(DemoData::getId, e -> e));
Map<Integer, List<DemoData>> pIdToChildrenListMap = sources.stream().collect(Collectors.groupingBy(DemoData::getPid));
List<Integer> willBeRemovedIdList = new LinkedList<>();
for (Map.Entry<Integer, List<DemoData>> entry : pIdToChildrenListMap.entrySet()) {
DemoData demoData = sourceMap.get(entry.getKey());
if (demoData == null) {
continue;
}
demoData.setChildren(entry.getValue().stream().sorted(Comparator.comparing(DemoData::getSort)).collect(Collectors.toList()));
willBeRemovedIdList.add(entry.getKey());
}
willBeRemovedIdList.forEach(pIdToChildrenListMap::remove);
// 获取顶级
return pIdToChildrenListMap.values().stream().flatMap(Collection::stream).sorted(Comparator.comparing(DemoData::getSort)).collect(Collectors.toList());
}




标签:JAVA,pIdToChildrenListMap,stream,List,Tree,DemoData,sources,entry
From: https://blog.51cto.com/u_6364219/5777681

相关文章

  • java连接ranger+ldap认证的hive
        使用java连接ranger+ldap认证的hive,通过jdbc加上用户名密码即可,代码示例如下:importjava.sql.*;publicclassJdbcHiveLdap{privatestaticString......
  • Javascript--变量内函数句柄
    <!DOCTYPEhtml><html><head><metacharset="utf-8"><title>菜鸟教程(runoob.com)</title></head><body><p>创建和使用对象方法。</p><p>对象方法作为一个函数定义存储......
  • 多测师肖sir__java__开班流程01
    开班流程:一、基本操作1、wifi连接网络教室1:dcs1或者5g密码:duoceshi999教室2:dcs2或者5g密码:duoceshi888教室3:dcs3或者5g密码:duoceshi666登陆密码:duoceshi666教室5:dcs5......
  • java连接sqlserver的方法分享
    转自:http://www.java265.com/JavaJingYan/202206/16552126983712.htmlsqlserver:   SQLServer是由Microsoft开发和推广的关系数据库管理系统(DBMS),它最初是由Micros......
  • Layui+treetable树实现 权限菜单多选单选
    HTML代码 所需文件我也一并上传链接:https://pan.baidu.com/s/1bAB2Pf5Dp5BDqEsMyrmWow?pwd=6666提取码:6666  效果图  需要注意的是这个不用多维数组但是要......
  • Java数组快速排序
    https://blog.csdn.net/weixin_44194075/article/details/1138504761.快速排序的思想​通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的......
  • 【转】【Java异常】idea 报错:无效的目标发行版:17 的解决办法
    原文地址:https://blog.csdn.net/weixin_44299027/article/details/120848738一、项目背景最近在看Spring源码书籍,从GitHub把Spring源码拉取下来之后,想写个Demo跟踪源码。......
  • java基础
    Before单行注释、多行注释 单行注释和多行注释内容不参与编译,编译以后生成的.class的字节码文件中不包含注释掉的信息。文档注释(java特有)文档注释内容可以被JDK提供的......
  • Java中HashMap的几种遍历方式
    publicstaticvoidmain(String[]args){Map<String,Object>map=newHashMap<>();map.put("姓名","张三");map.put("年龄",30);......
  • Java NIO中的Buffer类
    Buffer类当应用程序进行数据传输的时候,往往需要使用缓冲区,常用的缓存区就是JDKNIO类库提供的java.nio.Buffer;NIO的Buffer本质上是一个内存块,既可以写入数据,也可以从中......