简体   繁体   中英

Java Iterate Over List

How do you iterate over a list that has a "parent/child/grandChild/etc."?

Sample data:

{ID, Parent ID}

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

And the list would be, {parent, childA, childB, grandChildA, grandChildB}

How do you iterate it by "roots"?

Sample output:

  • Parent
    • ChildA
      • GrandChildB
    • ChildB
      • GrandChildA

Thanks!

Sample data:

Constructor: 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);

I then placed the objects in an ArrayList: ArrayList testList

so, problem is, how to iterate over the list, so that the result would:

  • Parent
    • ChildA
      • GrandChildB
    • ChildB
      • GrandChildA

I do recommend a tree-like data structure, such as:

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);
         }
      }
   }

}

Will print:

Parent
   ChildA
      GrandChildA
   ChildB
      GrandChildB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM