-->

Sorted maps in groovy

2020-02-19 05:53发布

问题:

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?

回答1:

If you just declare a map like so:

def m = [:]

Then, you can see Groovy by default makes a LinkedHashMap

assert m.getClass().name == 'java.util.LinkedHashMap'

If you look at the documentation for LinkedHashMap it says:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

So LinkedHashMap has an order, and you can affect that order in Groovy by calling sort

def m = [ b:1, a:2 ]

// Sort by descending value
m = m.sort { -it.value }

println m // prints [a:2, b:1]

If you want natural ordering of the keys, then you can use one of Java's sorted maps, such as TreeMap

To Say you want to use this in Groovy, you can do:

// def tm = [ tim_yates:1, F21:2 ] as TreeMap // works as well
TreeMap tm = [ tim_yates:1, F21:2 ]

Then printing this, you can see it is ordered by the keys:

println map // prints [F21:b, tim_yates:a]

A TreeMap will maintain order as you add keys. A LinkedHashMap will not automatically remain sorted when you add new values.



标签: java groovy map