Tapas Bose Tapas Bose - 1 year ago 117
Java Question

How to implement Stack Iteration using Java 8 Stream

I have a

Stack<Object>
and following piece of code:

while(!stack.isEmpty()){
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?

Answer Source

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()) {
    Stream.iterate(stack.pop(), 
                   e -> !stack.isEmpty(), 
                   e -> stack.pop())
          ...
}