javalistloopsrecursiondo-while

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


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