Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorted maps in groovy

Tags:

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?

like image 577
F21 Avatar asked Nov 16 '12 04:11

F21


People also ask

How do I sort a map in Groovy?

Maps don't have an order for the elements, but we may want to sort the entries in the map. Since Groovy 1.7. 2 we can use the sort() method which uses the natural ordering of the keys to sort the entries. Or we can pass a Comparator to the sort() method to define our own sorting algorithm for the keys.

How do I add a map to Groovy?

Add Item to a Map There are few ways to add item or values to a map. The first way is using the square brackets for the key. This way useful if you have a dynamic key name for example the key name join with index. The second way is using a key separate with map name by a dot ".".

Can map be sorted on values?

A map is not meant to be sorted, but accessed fast. Object equal values break the constraint of the map. Use the entry set, like List<Map.


1 Answers

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.

like image 100
tim_yates Avatar answered Oct 02 '22 14:10

tim_yates