SourMonk
SourMonk

Reputation: 344

Best way to iterate an object with a list of objects in Java

I am using Java to try and recursively iterate an object. To simplify my example, let's say this class is called Simple, and it contains an ID and a list that could contain between 0-n other Simple objects, and those Simple objects have a list that could contain between 0-n other Simple objects, etc.

What I want to do is pass a Simple and an ID, and have my method return the Simple that matches that ID. Below is the method I have written:

public static Simple getSimpleById(Simple simple, int id) {
    if (simple.getId() == id) {
        return simple;
    } else {
        for (Simple s : simple.getSimpleList()) {
            return getSimpleById(s, id);
        }
    }
    return null; // no match found
}

The problem is with the recursive method call -- with a return statement, my method exits as soon as it hits a Simple that has an empty list. Without the return statement, when a match is found, the Simple is returned to the caller and the method just keeps on iterating.

Can I accomplish what I need to do with recursion or am I barking up the wrong tree? I think it's the lists that are causing the issue here, is there a better way to do this?

Upvotes: 1

Views: 781

Answers (1)

Murat Karagöz
Murat Karagöz

Reputation: 37584

Change it to

 for (Simple s: simple.getSimpleList()) {
     Simple simple = getSimpleById(s, id);
     if (simple != null) return simple;
 }

Upvotes: 3

Related Questions