我有兴趣在 groovy 中使用排序 map (使用 gremlin,它是图形数据库的 DSL)。
我看过这个blog post在这里分类 map 上,但我还是有点困惑。
排序映射是如何声明的?它与 map
y = [:]
的标准方式有什么不同吗?使用排序映射时,插入列表的项目是否按照插入的顺序排列?还是我必须在排序映射中的项目排序之前运行
sort{}
?
最佳答案
如果你像这样声明一个 map :
def m = [:]
然后,您可以看到 Groovy 默认生成一个 LinkedHashMap
assert m.getClass().name == 'java.util.LinkedHashMap'
如果您查看 documentation for LinkedHashMap它说:
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
def m = [ b:1, a:2 ]
// Sort by descending value
m = m.sort { -it.value }
println m // prints [a:2, b:1]
如果你想要键的自然排序,那么你可以使用 Java 的排序映射之一,例如 TreeMap
如果您想在 Groovy 中使用它,您可以:
// def tm = [ tim_yates:1, F21:2 ] as TreeMap // works as well
TreeMap tm = [ tim_yates:1, F21:2 ]
然后打印这个,你可以看到它是按键排序的:
println map // prints [F21:b, tim_yates:a]
TreeMap
将在您添加键时保持顺序。当您添加新值时,LinkedHashMap
不会自动保持排序。
关于java - groovy 中的排序 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13410551/