java中将一维list集合转树形结构

添加工具类:

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

public class SoMap extends LinkedHashMap<String, Object> {

	private static final long serialVersionUID = 1L;

	/** 以下元素会在isNull函数中被判定为Null, */
	public static final Object[] NULL_ELEMENT_ARRAY = {null, ""};
	public static final List<Object> NULL_ELEMENT_LIST;
	static {
		NULL_ELEMENT_LIST = Arrays.asList(NULL_ELEMENT_ARRAY);
	}
		/** 将一个对象集合解析成为SoMap集合 */
	public static List<SoMap> getSoMapByList(List<?> list) {
		List<SoMap> listMap = new ArrayList<SoMap>();
		for (Object model : list) {
			listMap.add(getSoMapByModel(model));
		}
		return listMap;
	}

	/** 将一个对象集合解析成为SoMap */
	public static SoMap getSoMapByModel(Object model) {
		return SoMap.getSoMap().setModel(model);
	}
	/** 构建一个SoMap并返回 */
	public static SoMap getSoMap() {
		return new SoMap();
	}

	/** 如果为空,则返回默认值 */
	public Object get(Object key, Object defaultValue) {
		Object value = get(key);
		if(valueIsNull(value)) {
			return defaultValue;
		}
		return value;
	}
	/** set一个值,连缀风格 */
	public SoMap set(String key, Object value) {
		// 防止敏感key
		if(key.toLowerCase().equals("this")) {
			return this;
		}
		put(key, value);
		return this;
	}

	/** 将一个对象解析塞进SoMap */
	public SoMap setModel(Object model) {
		if(model == null) {
			return this;
		}

        // 会将该类的所以父级遍历一遍并获取值
		Class<?> objClass = model.getClass();
		// 遍历类层次结构
		while (objClass != null && objClass != Object.class) {
			// 获取声明的字段
			Field[] fields = objClass.getDeclaredFields();
			for (Field field : fields) {
				try {
					field.setAccessible(true); // 确保可以访问私有字段
					if (!Modifier.isStatic(field.getModifiers())) {
						// 将字段名和字段值添加到映射中
						this.set(field.getName(), field.get(model));
					}
				} catch (IllegalAccessException e) {
					throw new RuntimeException("Error accessing field: " + field.getName(), e);
				}
			}
			// 移动到父类
			objClass = objClass.getSuperclass();
		}

        //只解析本类
		Field[] fields = model.getClass().getDeclaredFields();
		for (Field field : fields) {
			try{
				field.setAccessible(true);
				boolean isStatic = Modifier.isStatic(field.getModifiers());
				if(!isStatic) {
					this.set(field.getName(), field.get(model));
				}
			}catch (Exception e){
				throw new RuntimeException(e);
			}
		}
		return this;
	}


	/** 指定value在此SoMap的判断标准中是否为null */
	public boolean valueIsNull(Object value) {
		return NULL_ELEMENT_LIST.contains(value);
	}

	/**
	 * 将一个一维集合转换为树形集合
	 * @param list         集合
	 * @param idKey        id标识key
	 * @param parentIdKey  父id标识key
	 * @param childListKey 子节点标识key
	 * @return 转换后的tree集合
	 */
	public static List<SoMap> listToTree(List<SoMap> list, String idKey, String parentIdKey, String childListKey) {
		// 声明新的集合,存储tree形数据
		List<SoMap> newTreeList = new ArrayList<SoMap>();
		// 声明hash-Map,方便查找数据
		SoMap hash = new SoMap();
		// 将数组转为Object的形式,key为数组中的id
		for (int i = 0; i < list.size(); i++) {
			SoMap json = (SoMap) list.get(i);
			hash.put(json.getString(idKey), json);
		}
		// 遍历结果集
		for (int j = 0; j < list.size(); j++) {
			// 单条记录
			SoMap aVal = (SoMap) list.get(j);
			// 在hash中取出key为单条记录中pid的值
			SoMap hashVp = (SoMap) hash.get(aVal.get(parentIdKey, "").toString());
			// 如果记录的pid存在,则说明它有父节点,将她添加到孩子节点的集合中
			if (hashVp != null) {
				// 检查是否有child属性,有则添加,没有则新建
				if (hashVp.get(childListKey) != null) {
					@SuppressWarnings("unchecked")
					List<SoMap> ch = (List<SoMap>) hashVp.get(childListKey);
					ch.add(aVal);
					hashVp.put(childListKey, ch);
				} else {
					List<SoMap> ch = new ArrayList<SoMap>();
					ch.add(aVal);
					hashVp.put(childListKey, ch);
				}
			} else {
				newTreeList.add(aVal);
			}
		}
		return newTreeList;
	}

	public String getString(String key) {
		Object value = get(key);
		if(value == null) {
			return null;
		}
		return String.valueOf(value);
	}
}

使用方法

@Override
public List<SoMap> getAll(String name,Integer ftype) {
    // 查询数据列表
	List<StreamProxyItem> streamProxyItems = testMapper.selectAll(name, ftype);
    // 将列表转为SoMap类型,注意(上面查询出来的StreamProxyItem类有没有父类,getSoMapByList方法里有只解析本类、解析所以父类的操作)
	List<SoMap> soMapByList = SoMap.getSoMapByList(streamProxyItems);
    // 将soMapByList列表转为树形结构:listToTree参数(SoMap列表,主键唯一值字段,父id字段,子节点标识)
	List<SoMap> soMaps = SoMap.listToTree(soMapByList, "id", "fid", "children");
	return soMaps;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值