Java迭代列表

时间:2015-09-11 07:28:47

标签: java arraylist

如何迭代具有“parent / child / grandChild / etc。”的列表?

示例数据:

{ID,Parent ID}

Object parent = {1, 0};
Object childA = {2, 1};
Object childB = {3, 1};
Object grandChildA = {4, 3};
Object grandChildB = {5, 2};

列表是{parent, childA, childB, grandChildA, grandChildB}

你如何通过“根”进行迭代?

示例输出:

    • ChildA
      • GrandChildB
    • ChildB
      • GrandChildA

谢谢!

示例数据:

构造函数:SampleObject(int id,int parentId)

SampleObject parent = new SampleObject(1, 0);
SampleObject childA = new SampleObject(2, 1);
SampleObject childB = new SampleObject(3, 1);
SampleObject grandChildA = new SampleObject(4, 3);
SampleObject grandChildB = new SampleObject(5, 2);

然后我将对象放在ArrayList:ArrayList testList

所以,问题是,如何遍历列表,以便结果如下:

    • ChildA
      • GrandChildB
    • ChildB
      • GrandChildA

1 个答案:

答案 0 :(得分:2)

我建议使用树状数据结构,例如:

package com.stackoverflow.test;

import java.util.ArrayList;
import java.util.List;

public class TreeNode {
   private String         name       = "";
   private List<TreeNode> childNodes = new ArrayList<TreeNode>();

   public TreeNode(final String name) {
      this.name = name;
   }

   public String getName() {
      return this.name;
   }

   public void add(final TreeNode child) {
      childNodes.add(child);
   }

   public List<TreeNode> getChildren() {
      return this.childNodes;
   }

   public static void main(String[] args) {

      TreeNode parent = new TreeNode("Parent");

      TreeNode childA = new TreeNode("ChildA");
      childA.add(new TreeNode("GrandChildA"));

      TreeNode childB = new TreeNode("ChildB");
      childB.add(new TreeNode("GrandChildB"));

      parent.add(childA);
      parent.add(childB);

      TreeNode.printRecursively(parent, 0);
   }

   private static void printRecursively(final TreeNode root, final int level) {
      if (null != root && null != root.getChildren()) {

         for (int i = 0; i < level; ++i) {
            System.out.print("   ");
         }

         System.out.println(root.getName());

         for (TreeNode child: root.getChildren()) {
            TreeNode.printRecursively(child, level + 1);
         }
      }
   }

}

将打印:

Parent
   ChildA
      GrandChildA
   ChildB
      GrandChildB