Tapas Bose Tapas Bose - 3 months ago 25x
Java Question

How to implement Stack Iteration using Java 8 Stream

I have a

and following piece of code:

Object object = stack.pop();
// do some operation on object

How this iteration can be implemented using Java 8 Stream so that it loops until the stack is empty and in every iteration the stack should be reduce by popping one element from top?


In Java 9, there will be a 3-arg version of Stream.iterate (like a for loop -- initial value, lambda for determining end-of-input, lambda for determining next input) that could do this, though it would be a little strained:

if (!stack.isEmpty()) {
                   e -> !stack.isEmpty(), 
                   e -> stack.pop())