groovy 中的排序映射 [英] Sorted maps in groovy

查看:13
本文介绍了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.

  • 排序映射是如何声明的?它与地图y = [:]的标准方式有什么不同吗?

  • How are sorted maps declared? Is it any different from the standard way for maps y = [:]?

使用排序映射时,插入到列表中的项目是否按照它们插入的顺序?或者我是否必须在排序映射中的项目排序之前运行 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 ]

然后打印这个,你可以看到它是按key排序的:

Then printing this, you can see it is ordered by the keys:

println map // prints [F21:b, tim_yates: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆