Sorted maps in groovy

前端 未结 1 712
暗喜
暗喜 2020-12-25 15:07

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 sti

相关标签:
1条回答
  • 2020-12-25 15:49

    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.

    0 讨论(0)
提交回复
热议问题