这几天写一个父子节点的数据规整,在网上找了一些方法,都太繁琐,自己写了一个,感觉比较简单,分享给大家
先说一下原理
第一,我们从数据库中将需要的数据查询出来,得到一个Object集合的list
第二,定义一个map,key为id,value为Object,这个的目的是为了方便后面的查找
第三,遍历第一步中查询到的数据集合list,取出Object中的parentid,根据parentid从第二步map中取出它的父节点,将其放入到父节点中去
第四,删除map中父节点parentid不为空的数据,这样我们的数据结构就组成了。
这里主要使用了java在参数传递时,如果参数是一个object时,那么它传递的是引用这么一个思想来进行实现,贴出代码供大家参考
public class Test {
public List<Goal> test(List<Goal> listGoal) {
Map<Integer, Goal> goalMap = new HashMap<Integer, Goal>();
for (Goal g : listGoal) {
int id = g.getId();
goalMap.put(id, g);
}
for (Goal g : listGoal) {
int pid = g.getParentId();
if (pid != 0) {
Goal tempGoal = goalMap.get(pid);
List<Goal> tempListGoal = tempGoal.getListGoal();
if (tempListGoal == null) {
tempListGoal = new ArrayList<Goal>();
}
tempListGoal.add(g);
tempGoal.setListGoal(tempListGoal);
}
}
List<Integer> list = new ArrayList<Integer>();
for (Integer k : goalMap.keySet()) {
Goal tempGoal = goalMap.get(k);
if (tempGoal.getParentId() != 0) {
list.add(k);
}
}
for (int i : list) {
goalMap.remove(i);
}
return new ArrayList<Goal>(goalMap.values());
}
public static void main(String[] args) {
List<Goal> listGoal = new ArrayList<Goal>();
Goal g1 = new Goal();
g1.setId(1);
g1.setParentId(0);
g1.setGoalName("g1");
Goal g2 = new Goal();
g2.setId(2);
g2.setParentId(1);
g2.setGoalName("g2");
Goal g3 = new Goal();
g3.setId(3);
g3.setParentId(2);
g3.setGoalName("g3");
Goal g4 = new Goal();
g4.setId(4);
g4.setParentId(2);
g4.setGoalName("g4");
Goal g5 = new Goal();
g5.setId(5);
g5.setParentId(3);
g5.setGoalName("g5");
Goal g6 = new Goal();
g6.setId(6);
g6.setParentId(0);
g6.setGoalName("g6");
Goal g7 = new Goal();
g7.setId(7);
g7.setParentId(3);
g7.setGoalName("g7");
Goal g8 = new Goal();
g8.setId(8);
g8.setParentId(7);
g8.setGoalName("g8");
Goal g9 = new Goal();
g9.setId(9);
g9.setParentId(7);
g9.setGoalName("g9");
Goal g10 = new Goal();
g10.setId(10);
g10.setParentId(4);
g10.setGoalName("g10");
Goal g11 = new Goal();
g11.setId(11);
g11.setParentId(10);
g11.setGoalName("g1");
Goal g12 = new Goal();
g12.setId(12);
g12.setParentId(7);
g12.setGoalName("g12");
Goal g13 = new Goal();
g13.setId(13);
g13.setParentId(0);
g13.setGoalName("g13");
listGoal.add(g1);
listGoal.add(g2);
listGoal.add(g3);
listGoal.add(g4);
listGoal.add(g5);
listGoal.add(g6);
listGoal.add(g7);
listGoal.add(g8);
listGoal.add(g9);
listGoal.add(g10);
listGoal.add(g11);
listGoal.add(g12);
listGoal.add(g13);
Test t = new Test();
List<Goal> listT = t.test(listGoal);
System.out.println(listT);
}