Order maintained when creating map from list and then creating list using Java Streams

54 Views Asked by At

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) {
...
}
1

There are 1 best solutions below

4
Eran On BEST ANSWER

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.