I have this Person class which has a list of Person (s). How do I loop through persons and check if each object inside of that has a list of Person(s) and if each object inside that has a list and so on and so forth? Everything I can think of is pretty limiting as far as how nested it gets. I can write a recursive loop but that gets me to the first level deep, but not sure how to get x levels deep with recursion. I am sure somebody has come accross this problem in the past and it shouldn't be that difficult but I just can't quite wrap my head around it. Any and all ideas are welcomed!
public class Person {
// other fields removed for simplicity
private long id;
private List<Person> persons;
public List<Person> getPersons() {
return debates;
}
}
// essentially I am looking for a way to make this unlimited level nested looping
private void loopPersons() {
Person person = new Person();
if(person.getPersons() != null && !person.getPersons().isEmpty()) {
for(Person person1 : person.getPersons()) {
if(person1.getPersons() != null && !person1.getPersons().isEmpty()) {
System.out.println(person1.getId());
for(Person person2 : person1.getPersons()) {
if(person2.getPersons() != null && !person2.getPersons().isEmpty()) {
System.out.println(person2.getId());
}
}
}
}
}
}
UPDATE: The answer by Brian in this other post (scroll down) is essentially what does it. iterate through recursive objects