I want to understand behavior of Stack class when used with Java 8 streams API.
Stack<Integer> s = new Stack<>();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.stream().forEach( x-> System.out.print(x + " "));
As per the contract of Stack class, this code should print 4 3 2 1
.
But instead, it prints 1 2 3 4
.
Basically I want to Understand:
Underlying low level implementation details that is causing this behavior.
Any other known pitfalls like this when using Stream API to Iterate Ordered collections.
If I wanted to implement my own Stack class, which plays wells with Java 8 Streams, what changes are needed ?
Misconception: the stream()
method comes out of the Collection interface.
And its javadoc tells us:
Returns a sequential Stream with this collection as its source.
In other words: the "Stream contract" doesn't know or care about the "Stack contract".
Beyond that, that "Stack contract" is about "Stack operations". In other words: there is no guarantee about ordering of elements when iterating a Stack via streams.
And, javadoc from Stack itself tells us:
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack.
So, you got it right there: A Stack is nothing but a vector (list), that provides additional operations that enable "Stack behavior". You can see that here:
for (Integer i : s) {
System.out.println(i);
}
So, even when "just" iterating your stack, leaving out the streamish part, it will print the elements in insertion order 1, 2, 3, 4.