大深度的树结构数据容易导致堆的内存溢出
package org.amaidan.common.utils;
import cn.hutool.system.SystemUtil;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 树结构数据处理
* @author Joen
* @since 2023-03-28 10:19:01
*/
public class TreeUtils<T> {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(10);
TreeUtils<Test1> utils = TreeUtils.getInstance(seed -> {
int i1 = i.getAndDecrement();
if (i1 > 0){
i.set(i1 - 1);
List<Test1> test1s = new ArrayList<>();
for (int j = 11 - i1;j > 0;j--){
Test1 test1 = new Test1();
test1.setId(SystemUtil.getCurrentPID());
test1s.add(test1);
}
return test1s;
}
return null;
}, Test1::setTest1s);
System.out.println(JSON.toJSONString(utils.tree(null)));
}
private U<T> u;
private C<T> c;
public static <T> TreeUtils<T> getInstance(U<T> u, C<T> c) {
TreeUtils<T> utils = new TreeUtils<>();
utils.u = u;
utils.c = c;
return utils;
}
public List<T> tree(T seed) {
List<T> list = u.iti(seed);
T curve;
Cache<T> curveCa = new Cache<>(list, null);
for (; ; ) {
if (curveCa == null || (curve = curveCa.next()) == null) {
return list;
}
List<T> iti = u.iti(curve);
c.setChild(curve, iti);
if (iti != null && iti.size() > 0) {
curveCa = new Cache<>(iti,curveCa);
}else {
curveCa = curveCa.getParent();
}
}
}
@Data
public static class Test1 {
private Long id;
private List<Test1> test1s;
}
@Data
public static class Cache<T> {
public Cache(List<T> list, Cache<T> parent) {
this.list = list;
this.parent = parent;
}
private List<T> list;
private Integer index = 0;
public T next() {
if (list == null || list.size() == index){
return null;
}
return list.get(index++);
}
private Cache<T> parent;
}
@FunctionalInterface
public interface U<T> {
List<T> iti(T seed);
}
@FunctionalInterface
public interface C<T> {
void setChild(T t, List<T> list);
}
}