Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return object from loop with recursion

it found need object, but always returns null.
I have infinity inner lists

private static Budget recursion(Budget budget, long sec) {
    boolean flag;

    do {
        flag = false;
        if (Objects.equals(budget.getSection(), sec)) {
            return budget;
        }
        budget.getSubBudget().forEach(b -> recursion(b, sec));

    } while (flag);

    return null;
}

if print result in if() condition it works well

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code ignores what the recursive call returns. It could be the object you are interested in, but your forEach will just discard that information and keep on looping. The while loop serves no purpose, as in each iteration you would check the same objects, and flag is never set to true.

Not related, but you don’t need Object.equals to compare long values.

You’ll want something like this:

private static Budget recursion(Budget budget, long sec) {
    if (budget.getSection() == sec) {
        return budget;
    }
    for (Budget b : budget.getSubBudget()) {
        Budget result = recursion(b, sec);
        if (result != null) {
           return result; 
        }
    }
    return null;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading