Using Java streams, we have a list of items, and for each item we want to calculate some value and then return a list of these values, using the original order. Will the following code always preserve the ordering? After all, a map is not an ordered data structure.
List<Item> list;
list.stream()
.map(item -> calculateValue(item))
.toList();
...
private double calculateValue(Item item) {
...
}
The
map()intermediateStreamoperation does not produce aMapinstance. It just applies theFunctionyou pass to it on each element of theStream. Therefore, the order of the elements of the originalListwill be preserved in the outputList.