Tapas Bose Tapas Bose - 5 months ago 47
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

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())
          ...
}