user2142786
user2142786

Reputation: 1482

How to iterate a list inside a list in java?

Hi i have two value object classes .

package org.array;

import java.util.List;



public class Father {

    private String name;
    private int age ;
    private List<Children> Childrens;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public List<Children> getChildrens() {
        return Childrens;
    }
    public void setChildrens(List<Children> childrens) {
        Childrens = childrens;
    }


}

second is for children

package org.array;

public class Children {

    private String name;
    private int age ;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }


}

and i want to print there value i nested a list inside a list here i am putting only a single value inside the objects while in real i have many values . so i am nesting list of children inside father list. how can i print or get the value of child and father both. here is my logic.

package org.array;

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

public class ArrayDemo {

    public static void main(String[] args) {
         List <Father> fatherList = new ArrayList<Father>();
        Father father =  new Father();
        father.setName("john");
        father.setAge(25);
        fatherList.add(father);

         List <Children> childrens = new ArrayList<Children>();
         Children children = new Children();
        children.setName("david");
        children.setAge(2);
        childrens.add(children);
        father.setChildrens(childrens);
        fatherList.add(father);

        Iterator<Father> iterator = fatherList.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.toString());
        }



        }
        }

Upvotes: 2

Views: 40453

Answers (7)

Rajesh
Rajesh

Reputation: 4769

Iterating over List using Java 8 forEach.

{
            List<Father> fatherList = new ArrayList<Father>();
            // Create Father Object
            Father father = new Father();
            father.setName("john");
            father.setAge(25);
            List<Children> childrens = new ArrayList<Children>();
            // Create child object
            Children children = new Children();
            children.setName("david");
            children.setAge(2);
            childrens.add(children);
            father.setChildrens(childrens);
            fatherList.add(father);
            fatherList.forEach(f -> {
                System.out.println("Father's Name : " + f.getName());
                f.getChildrens().forEach(c -> {
                    System.out.println("Children's Name : " + c.getName());
                });
            });
        }

Upvotes: 0

Shishir Kumar
Shishir Kumar

Reputation: 8201

Just to print the objects, you may use below code snippet

       for (Father father2 : fatherList) {
            System.out.print("Father: "+ReflectionToStringBuilder.toString(father2));
            for (Children children2 : childrens) {
                System.out.print(" Children: " + ReflectionToStringBuilder.toString(children2));
            }
            System.out.println();
        }

Upvotes: 1

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

Override toString() in Father and Children. Your toString() implementation of Father should use children.toString() to build the resultant string and that is it. Then printing the father will print the details of father and children both.

Children implementation of toString()

public String toString() {
StringBuffer buff = new StringBuffer();
    buff.append("[Name : ");
    buff.append(this.name).append(", Age : ");
    buff.append(this.age);
    buff.append("]");
    return buff.toString();
}

Father implementation of toString()

@Override
public String toString() {
    StringBuffer buff = new StringBuffer();
    buff.append("[ Father Name : ");
    buff.append(this.name);
    buff.append(", Age : ");
    buff.append(this.age);
    buff.append(", Childrens : { ");
    for (Children children : getChildrens()) {
        buff.append(children);
        buff.append(" ");
    }
    buff.append("}");
    return buff.toString();
}

Then printing Father will print the information about Father and Children both.

System.out.println(father);

Upvotes: 1

Marc Baumbach
Marc Baumbach

Reputation: 10473

You can use a nested for loop to accomplish this. Here's an example:

for (Father f : fatherlist) {
    System.out.println("Father: " + f.getName());
    System.out.println("Children:");
    for (Children c : f.getChildrens()) {
        System.out.println(c.getName());
    }
}

Using the Iterator approach, you would accomplish it this way:

Iterator<Father> i = fatherList.iterator();
while (i.hasNext()) {
    Father f = i.next();
    System.out.println("Father: " + f.getName());
    System.out.println("Children:");
    Iterator<Children> ci = f.getChildrens().iterator();
    while (ci.hasNext()) {
        Children c = ci.next();
        System.out.println(c.getName());
    }
}

As a general style suggestion, I would suggest renaming the Children class to Child and rename the methods getChildrens and setChildrens in Father to getChildren and setChildren respectively.

I would even suggest taking it a step further and remove the setChildren method and provide an addChild(Child child) method such that you have control over the List that contains the children. A benefit to this is that you can guarantee a List is instantiated such that these loops you are defining won't hit a NullPointerException in the case that no children were added to a particular Father instance.

Upvotes: 4

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can use the advance forloop for iterating (which is equals to using iterator) child ArrayList and parent ArrayList

sample:

 for(Father  f : fatherList)
 {
    for(Children c : f.getChildrens)
    {

    }
 }

Upvotes: 1

Mohan Raj B
Mohan Raj B

Reputation: 1026

Simple use two for loops

for (Father f : fatherlist) {
    for (Children c : f.getChildrens) {
    }
}  

Upvotes: 0

75inchpianist
75inchpianist

Reputation: 4102

Iterator<Father> iterator = fatherList.iterator();
        while (iterator.hasNext()) {
           Father father = iterator.next();
              Iterator<Children> childiter = father.getChildren().iterator();
              while(childiter.hasNext()){
                  System.out.println(childiter.next().toString());
               }

        }

Upvotes: 1

Related Questions