排序的地图在groovy [英] Sorted maps in groovy
问题描述
我有兴趣在groovy中使用排序的地图(gremlin是图形数据库的DSL)。
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.
-
如何排序地图声明?是否与地图的标准方式有所不同?
使用排序地图,是插入到列表中的项目将按照插入的顺序?或者在排序地图中的项目排序之前,我必须运行 sort {}
?
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:
def m = [:]
然后,您可以看到Groovy默认使用 LinkedHashMap
Then, you can see Groovy by default makes a LinkedHashMap
assert m.getClass().name == 'java.util.LinkedHashMap'
如果您查看 LinkedHashMap的文档它说:
哈希表和链接列表实现的Map界面,具有可预测的迭代顺序。该实现与HashMap不同之处在于它保持双向链接列表的所有条目。此链接列表定义了迭代排序,通常是将键插入到地图(插入顺序)中的顺序。
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).
所以 LinkedHashMap
有一个订单,您可以通过调用 sort
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]
如果要自然排序键,则可以使用Java的排序映射之一,例如 TreeMap
If you want natural ordering of the keys, then you can use one of Java's sorted maps, such as TreeMap
如果您想在Groovy中使用,可以执行以下操作:
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
将在添加密钥时维护顺序。当您添加新值时, LinkedHashMap
将不会自动保持排序。
A TreeMap
will maintain order as you add keys. A LinkedHashMap
will not automatically remain sorted when you add new values.
这篇关于排序的地图在groovy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!