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()
intermediate Stream
operation does not produce a Map
instance. It just applies the Function
you pass to it on each element of the Stream
. Therefore, the order of the elements of the original List
will be preserved in the output List
.