I am interested in using a sorted map in groovy (with gremlin which is a DSL for graph databases).
I have looked at this blog post on sorted maps here, but I am still a bit confused.
-
How are sorted maps declared? Is it any different from the standard way for maps
y = [:]? -
When using a sorted map, are items inserted into the list going to be in the order they are inserted? Or will I have to run
sort{}before the items in the sorted map are sorted?
If you just declare a map like so:
Then, you can see Groovy by default makes a
LinkedHashMapIf you look at the documentation for LinkedHashMap it says:
So
LinkedHashMaphas an order, and you can affect that order in Groovy by callingsortIf you want natural ordering of the keys, then you can use one of Java’s sorted maps, such as
TreeMapTo Say you want to use this in Groovy, you can do:
Then printing this, you can see it is ordered by the keys:
A
TreeMapwill maintain order as you add keys. ALinkedHashMapwill not automatically remain sorted when you add new values.