Can anyone explain the difference between a for-loop and the forEach API in Iterable?


  • 1

    I get StackOverflow error if I'm using the forEach API (The commented line). So can anyone explain what is the difference between for-loop and forEach? And, what I'm most interested in is which one should we adopt in different scenarios?
    ...

    HashMap<Integer, UndirectedGraphNode> visited = new HashMap<>();
    
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;
        if (visited.containsKey(node.label)) return visited.get(node.label);
        
        UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
        visited.put(clone.label, clone);
        //node.neighbors.forEach(neighbor -> clone.neighbors.add(cloneGraph(neighbor)));
        for (UndirectedGraphNode neighbor: node.neighbors) clone.neighbors.add(cloneGraph(neighbor));
        
        return clone;
    }
    

    ...


  • 0

    @Joshua_LI I'm not an expert at this, but I'd say with forEach, you're calling the forEach function, which calls your lambda function, which calls the add function. So that's two more stack frames (with whatever is in them) compared to the for way, which calls the add function directly. I'm not really familiar with Java streaming, so I can't tell where it's really "better", except I sometimes use it if it makes my code simpler/shorter. And of course don't use it if it's too costly, like it is here.


  • 0
    This post is deleted!

  • 0

    @StefanPochmann Yes, now I can see at least for recursive calls it could be too costly to use forEach.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.