java - groovy 中的排序 map

标签 java groovy map

我有兴趣在 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

在 Groovy 中影响该顺序
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/

相关文章:

arrays - Array.map(f : A => B) in Scala) 性能不佳

java - 如何在Java中将整数的字节字符串打印到套接字?

unit-testing - 第三方对象的 Grails/Groovy 模拟动态属性

java - 为什么我们有不可变的空映射?

groovy - 我们可以让这个片段更精彩吗?

maven - gmaven 插件 : how to set property in pom. 用于外部 groovy 脚本的 xml

java - 使用 Java 按 HashMap 类中的值排序

java - 添加页脚所有页面文档

java - 获取单元格在 JXTreeTable 中的位置

java - 获取 HTTP 错误 : 500 on get response Json Object from glassfish Jersey Rest server