Reputation: 24068
List<MyObject> myList = new ArrayList<>();
//populate myList here
List<String> nameList = myList.stream()
.map(MyObject::getName)
.collect(Collectors.toList());
In above code, can I expect that order of MyObject
names in nameList
is always the same as the order of myList
?
Upvotes: 68
Views: 42209
Reputation: 100159
Yes, you can expect this even if you are using parallel stream as long as you did not explicitly convert it into unordered()
mode.
The ordering never changes in sequential mode, but may change in parallel mode. The stream becomes unordered either:
unordered()
callHashSet
stream is unordered as order is implementation dependent and you cannot rely on it)forEach()
operation or collecting to unordered collector like toSet()
)In your case none of these conditions met, thus your stream is ordered.
Upvotes: 92