Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Tapas Bose Avatar asked Mar 12 '23 19:03

Tapas Bose


1 Answers

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())
          ...
}
like image 128
Brian Goetz Avatar answered Mar 24 '23 01:03

Brian Goetz