Java把List集合转成树形结构
创始人
2024-11-10 05:40:11
0

1. 实体类

     org.projectlombok     lombok     1.18.22 
package com.utils;  import lombok.Data; import java.util.List;  /**  * @Description:  * @Author:   * @Date: 2021/12/16 9:35  */ @Data public class TestEntity {     private int id;     private String name;     private int parentId;          private List children;  }

2. 方法一:使用Stream流

private static List listToTree1(List list) {     // 要点     // 通过Collectors.groupingBy(Address::getPid)方法对addresses按照Pid进行分组,也就是将pid相同的放在一起     Map> parentMap = list.stream().collect(Collectors.groupingBy(TestEntity::getParentId));     list.forEach(item -> {         item.setChildren(parentMap.get(item.getId()));     });     // 过滤出根节点集合,根节点已经包含了孩子节点     List newList = list.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());     return newList; }

3. 方法二:使用fastjson

添加依赖

     com.alibaba     fastjson     1.2.73 
/** * @param list          :要转成树的集合 * @param keyMark       :id * @param parentKeyMark :pid * @param childMark     :children * @return List:树集合 * @description :如TestEntity中有字段    int id,String name,int parentId,List children字段 * keyMark、parentKeyMark、childMark就是    "id", "parentId", "children" */ public static List listToTree2(List list, String keyMark, String parentKeyMark, String childMark) {     JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(list));     JSONArray jsonArrayTree = new JSONArray();     JSONObject hash = new JSONObject();     //将数组转为Object的形式,key为数组中的id     for (int i = 0; i < jsonArray.size(); i++) {         JSONObject json = (JSONObject) jsonArray.get(i);         hash.put(json.getString(keyMark), json);     }     //遍历结果集     for (int j = 0; j < jsonArray.size(); j++) {         //单条记录         JSONObject aVal = (JSONObject) jsonArray.get(j);         //在hash中取出key为单条记录中pid的值         if (null != aVal.get(parentKeyMark) && !"".equals(aVal.get(parentKeyMark))) {             JSONObject hashVP = (JSONObject) hash.get(aVal.get(parentKeyMark).toString());             //如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中             if (hashVP != null) {                 //检查是否有child属性                 if (hashVP.get(childMark) != null) {                     JSONArray ch = (JSONArray) hashVP.get(childMark);                     ch.add(aVal);                     hashVP.put(childMark, ch);                 } else {                     JSONArray ch = new JSONArray();                     ch.add(aVal);                     hashVP.put(childMark, ch);                 }             } else {                 jsonArrayTree.add(aVal);             }         } else {             jsonArrayTree.add(aVal);         }     }     return jsonArrayTree.toJavaList(TestEntity.class); }

4. 方法三:使用递归

/** * 使用递归方法建树 * * @param list 要转成树的集合 * @return List */ public static List listToTree2(List list) {     List trees = new ArrayList<>();     for (TestEntity entity : list) {         int parentId = entity.getParentId();         if (parentId == 0) {             // 是父级             trees.add(findChildren(entity, list));         }     }     return trees; }  /** * 递归查找子节点 * * @param entity 对象 * @param list 子节点 * @return MenuTree */ private static TestEntity findChildren(TestEntity entity, List list) {     for (TestEntity info : list) {         if (entity.getId() == info.getParentId()) {             if (entity.getChildren() == null) {                 entity.setChildren(new ArrayList<>());             }             entity.getChildren().add(findChildren(info, list));         }     }     return entity; }

5. 完整测试类

package list;  import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject;  import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors;  public class ListToTreeTest {     public static void main(String[] args) {         List list = new ArrayList<>();          TestEntity testEntity1 = new TestEntity();         testEntity1.setId(1);         testEntity1.setName("张三");         testEntity1.setParentId(0);          TestEntity testEntity2 = new TestEntity();         testEntity2.setId(2);         testEntity2.setName("李四");         testEntity2.setParentId(0);          TestEntity testEntity3 = new TestEntity();         testEntity3.setId(3);         testEntity3.setName("张三儿子");         testEntity3.setParentId(1);          list.add(testEntity1);         list.add(testEntity2);         list.add(testEntity3);           List result1 = listToTree1(list);         System.out.println(result1);  //        List result2 = listToTree2(list, "id", "parentId", "children"); //        System.out.println(result2);  //        List result3 = listToTree3(list); //        System.out.println(result3);      }      private static List listToTree1(List list) {         // 要点         // 通过Collectors.groupingBy(Address::getPid)方法对addresses按照Pid进行分组,也就是将pid相同的放在一起         Map> parentMap = list.stream().collect(Collectors.groupingBy(TestEntity::getParentId));         list.forEach(item -> {             item.setChildren(parentMap.get(item.getId()));         });         // 过滤出根节点集合,根节点已经包含了孩子节点         List newList = list.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());         return newList;     }      /**      * @param list          :要转成树的集合      * @param keyMark       :id      * @param parentKeyMark :pid      * @param childMark     :children      * @return List:树集合      * @description :如TestEntity中有字段    int id,String name,int parentId,List children字段      * keyMark、parentKeyMark、childMark就是    "id", "parentId", "children"      */     public static List listToTree2(List list, String keyMark, String parentKeyMark, String childMark) {         JSONArray jsonArray = JSONArray.parseArray(JSONObject.toJSONString(list));         JSONArray jsonArrayTree = new JSONArray();         JSONObject hash = new JSONObject();         //将数组转为Object的形式,key为数组中的id         for (int i = 0; i < jsonArray.size(); i++) {             JSONObject json = (JSONObject) jsonArray.get(i);             hash.put(json.getString(keyMark), json);         }         //遍历结果集         for (int j = 0; j < jsonArray.size(); j++) {             //单条记录             JSONObject aVal = (JSONObject) jsonArray.get(j);             //在hash中取出key为单条记录中pid的值             if (null != aVal.get(parentKeyMark) && !"".equals(aVal.get(parentKeyMark))) {                 JSONObject hashVP = (JSONObject) hash.get(aVal.get(parentKeyMark).toString());                 //如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中                 if (hashVP != null) {                     //检查是否有child属性                     if (hashVP.get(childMark) != null) {                         JSONArray ch = (JSONArray) hashVP.get(childMark);                         ch.add(aVal);                         hashVP.put(childMark, ch);                     } else {                         JSONArray ch = new JSONArray();                         ch.add(aVal);                         hashVP.put(childMark, ch);                     }                 } else {                     jsonArrayTree.add(aVal);                 }             } else {                 jsonArrayTree.add(aVal);             }         }         return jsonArrayTree.toJavaList(TestEntity.class);     }      /**      * 使用递归方法建树      *      * @param list 要转成树的集合      * @return List      */     public static List listToTree3(List list) {         List trees = new ArrayList<>();         for (TestEntity entity : list) {             int parentId = entity.getParentId();             if (parentId == 0) {                 // 是父级                 trees.add(findChildren(entity, list));             }         }         return trees;     }      /**      * 递归查找子节点      *      * @param entity 对象      * @param list   子节点      * @return MenuTree      */     private static TestEntity findChildren(TestEntity entity, List list) {         for (TestEntity info : list) {             if (entity.getId() == info.getParentId()) {                 if (entity.getChildren() == null) {                     entity.setChildren(new ArrayList<>());                 }                 entity.getChildren().add(findChildren(info, list));             }         }         return entity;     } }

相关内容

热门资讯

今天下午!海盗来了辅助器无限炮... 今天下午!海盗来了辅助器无限炮!真是真的是有辅助app(有挂神器)-哔哩哔哩1、很好的工具软件,可以...
据文件显示!汇友游戏辅助!确实... 据文件显示!汇友游戏辅助!确实真的是有辅助app(竟然有挂)-哔哩哔哩1、实时汇友游戏辅助透视辅助更...
现有关情况通报如下!大菠萝提高... 现有关情况通报如下!大菠萝提高好牌几率!好像存在有辅助插件(今日头条)-哔哩哔哩大菠萝提高好牌几率是...
据通报!情怀破解!真是真的是有... 据通报!情怀破解!真是真的是有辅助软件(有挂分享)-哔哩哔哩1、下载好情怀破解脚本下载之后点击打开,...
无独有偶!心悦海南苹果版辅助!... 无独有偶!心悦海南苹果版辅助!切实有挂辅助平台(确实有挂)-哔哩哔哩1、很好的工具软件,可以解锁游戏...
现有关情况通报如下!新财神正版... 现有关情况通报如下!新财神正版辅助挂!原来存在有辅助挂(证实有挂)-哔哩哔哩1、超多福利:超高返利,...
据报道!闲逸官方辅助软件叫什么... 据报道!闲逸官方辅助软件叫什么名字!本来真的是有辅助下载(存在有挂)-哔哩哔哩1、首先打开闲逸官方辅...
现有关情况通报如下!丽水欢乐堂... 现有关情况通报如下!丽水欢乐堂辅助插件!竟然是真的辅助下载(有挂分享)-哔哩哔哩1、许多玩家不知道丽...
随着!微信小程序家乡大二辅助工... 随着!微信小程序家乡大二辅助工具!竟然真的有辅助挂(有挂头条)-哔哩哔哩微信小程序家乡大二辅助工具能...
据监测!拱趴大菠萝的辅助器!一... 据监测!拱趴大菠萝的辅助器!一直是真的辅助下载(讲解有挂)-哔哩哔哩1、每一步都需要思考,不同水平的...