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?
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())
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With