Back in March 2023 there was a discussion about the non-deterministic
iteration order of Map.of() and friends:
https://mail.openjdk.org/pipermail/core-libs-dev/2023-March/102865.html

It feels like this discussion should be revisited now that we have
StableValue. Map.of() is one of the few ways (along with method
references and records) that we have at the moment to ensure a chain
of trust through for the JVM so it can constant fold. This should (if
people are aware) push more people to use Map.of() and friends.

The unspecified iteration order is a problem however. In most use
cases I have had where Map.of() was viable, I had to revert it or not
use it because of the iteration order. IMO, it is fundamentally
surprising that the order I enter the data in source code is not
retained. More generally, in my experience it is much better for a
large codebase to consistently use LinkedHashMap over HashMap as it
means that the output is always consistent.

My recent use case was in code generation to store a map of bean
properties so that the order matches that seen in source code
(something that reflection still doesn't supply). The only way this
could be done today would be for me to store both a List for the order
and a Map for the data, which is wasteful and error prone.

The basic options here are:
- developers manually hold both a List and Map (very error prone)
- developers write their own Map using  record as the implementation
tool (hacky)
- change Map.of() to have a fixed iteration order (allowed by the
spec, and IMO what most devs expect)
- add SequencedMap.of() or Map.ofOrdered() to allow devs to choose
iteration order

In summary, the current Map.of() is a bit of a hand grenade IMO, and
something I pretty much banned at my previous company. Which is a
problem given its key role in StableValue.

Stephen

Reply via email to