溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

深入淺析java中的轉(zhuǎn)樹形結(jié)構(gòu)工具類

發(fā)布時(shí)間:2020-11-07 15:23:42 來源:億速云 閱讀:199 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)深入淺析java中的轉(zhuǎn)樹形結(jié)構(gòu)工具類,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

具體內(nèi)容如下

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.ToString;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author : liyk
 * @version 1.0
 * @date : 2020/6/9 
 */
public class TreeUtil {


  /**
   * 將 List 轉(zhuǎn)為樹形結(jié)構(gòu)
   *
   * @param origList     : 要轉(zhuǎn)換的 List
   * @param idFieldName    : id字段名
   * @param parentIdFieldName : parentId 字段名
   * @param childrenFieldName : children 字段名
   * @param <T>        : 擁有父子結(jié)構(gòu)的 Entity
   * @return : 樹形結(jié)果
   * @throws Exception .
   */
  public static <T> List<T> convert(List<T> origList, String idFieldName,
                   String parentIdFieldName, String childrenFieldName) throws Exception {
    // 用于保存當(dāng)前 id 索引的實(shí)體類
    Map<String, T> idMaps = new HashMap<>();
    // 暫存區(qū), 用于保存沒有找到父 id 的控件
    List<T> tempList = new ArrayList<>();
    List<T> result = new ArrayList<>();
    for (T entity : origList) {
      // 獲取 id, parentId, children
      String id = Objects.toString(getFieldValue(entity, idFieldName), "");
      String parentId = Objects.toString(getFieldValue(entity, parentIdFieldName), "");
      if (StringUtils.isEmpty(id)) {
        throw new Exception("存在id為空的資料");
      }
      idMaps.put(id, entity);
      if (StringUtils.isEmpty(parentId)) {
        // 如果父 id 為空, 則實(shí)體類為第一層
        result.add(entity);
      } else {
        // 根據(jù)父 id 獲取實(shí)體類
        T parentEntity = idMaps.get(parentId);
        if (parentEntity == null) {
          // 沒找到先放入暫存區(qū)
          tempList.add(entity);
        } else {
          // 父組件判斷是否存在 children, 不存在新增, 存在則直接假如
          setChildrenValue(childrenFieldName, entity, parentEntity);
        }
      }
    }
    // 處理暫存區(qū), 暫存區(qū)的一定不為根節(jié)點(diǎn), 所以它只要父節(jié)點(diǎn)存在, 那么此輪查詢一定能找到父節(jié)點(diǎn)(上一輪已經(jīng)將全部節(jié)點(diǎn)放入 idMaps)
    for (T entity : tempList) {
      // 獲取 parentId
      String parentId = Objects.toString(getFieldValue(entity, parentIdFieldName), "");
      // 根據(jù)父id獲取實(shí)體類
      T parentEntity = idMaps.get(parentId);
      if (parentEntity == null) {
        throw new Exception("存在孤立的子節(jié)點(diǎn)");
      } else {
        // 父組件判斷是否存在children, 不存在新增, 存在則直接假如
        setChildrenValue(childrenFieldName, entity, parentEntity);
      }
    }
    return result;
  }

  private static <T> void setChildrenValue(String childrenFieldName, T entity, T parentEntity) throws Exception {
    Object children = getFieldValue(parentEntity, childrenFieldName);
    List<T> childrenList;
    if (children == null) {
      childrenList = new ArrayList<>();
      childrenList.add(entity);
      setFieldValue(parentEntity, childrenFieldName, childrenList);
    } else {
      List<T> childrenReal = (List<T>) children;
      childrenReal.add(entity);
    }
  }

  private static <T> Object getFieldValue(T entity, String fieldName) throws Exception {
    Field field = ReflectionUtils.findField(entity.getClass(), fieldName);
    if (field == null) {
      throw new Exception(String.format("字段名稱[%s]不存在", fieldName));
    }
    boolean accessible = field.isAccessible();
    field.setAccessible(true);
    Object result = ReflectionUtils.getField(field, entity);
    field.setAccessible(accessible);
    return result;
  }

  private static <T> void setFieldValue(T entity, String fieldName, Object value) throws Exception {
    Field field = ReflectionUtils.findField(entity.getClass(), fieldName);
    if (field == null) {
      throw new Exception(String.format("字段名稱[%s]不存在", fieldName));
    }
    boolean accessible = field.isAccessible();
    field.setAccessible(true);
    ReflectionUtils.setField(field, entity, value);
    field.setAccessible(accessible);
  }

  public static void main(String[] args) throws Exception {
    List<Demo> list = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
      Demo demo = new Demo(i, "一級節(jié)點(diǎn)" + i);
      list.add(demo);
    }
    for (int i = 5; i < 15; i++) {
      Demo demo = new Demo(i, i % 5, "二級節(jié)點(diǎn)" + i);
      list.add(demo);
    }
    for (int i = 15; i < 100; i++) {
      Demo demo = new Demo(i, i % 10 + 5, "三級節(jié)點(diǎn)" + i);
      list.add(demo);
    }
    Demo demo = new Demo(100, 102, "非法節(jié)點(diǎn)");
    list.add(demo);
    List<Demo> convert = TreeUtil.convert(list, "id", "pid", "children");
    String s = JSON.toJSONString(convert);
    System.out.println(s);
  }

}

@Data
@ToString
class Demo {
  private Integer id;
  private Integer pid;
  private String name;
  private List<Demo> children;

  public Demo(Integer id, Integer pid, String name) {
    this.id = id;
    this.pid = pid;
    this.name = name;
  }

  public Demo(Integer id, String name) {
    this.id = id;
    this.name = name;
  }
}

以上就是深入淺析java中的轉(zhuǎn)樹形結(jié)構(gòu)工具類,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI