按照Groovy中定义的键顺序对映射进行排序(Sort Map by Defined Order of Keys in Groovy)

编程入门 行业动态 更新时间:2024-10-25 00:36:49
按照Groovy中定义的键顺序对映射进行排序(Sort Map by Defined Order of Keys in Groovy)

我有一个配置文件来指定要从JSON文档中提取的字段,然后我要写入CSV文件。

目前,我正在遍历JSON文档,并将指定的键和值分配给HashMap<String,Object> ,然后将这些键添加到ArrayList<HashMap<String,Object>> 。 看起来这个地图是在JSON文档中读取信息时填充的。

如何将我的地图按照配置文件中指定的字段顺序排序? 我在网上搜索,但只发现如何按字母顺序或数字排序的例子,这不是我想要的。

配置: "useFields":["id","created","subject","status","priority"]

当前输出: ["created:16-Feb-2017, id:1234, priority:low, status:Foo, subject:Bar"]

期望输出: ["id:1234, created:16-Feb-2017, subject:Bar, status:Foo, priority:low"]

I have a configuration file to specify fields to extract from a JSON document, which I then want to write to a CSV file.

At the moment, I am iterating through the JSON document and assigning the specified keys and values to a HashMap<String,Object>, and then adding those to an ArrayList<HashMap<String,Object>>. It seems that the map is populated as the information is read from the JSON document.

How can I sort my maps to be in the order of the fields specified in the configuration file? I've searched online but only found examples on how to sort alphabetically or numerically which is not what I want.

Configuration: "useFields":["id","created","subject","status","priority"]

Current output: ["created:16-Feb-2017, id:1234, priority:low, status:Foo, subject:Bar"]

Desired output: ["id:1234, created:16-Feb-2017, subject:Bar, status:Foo, priority:low"]

最满意答案

标准Java类LinkedHashMap按照它们添加的顺序对映射条目进行排序。 事实证明,使用Groovy“map literal”语法时创建的实际对象实际上就是LinkedHashMap 。 因此,获得所需的效果与创建空地图文字以及按照所需顺序添加现有地图中的条目一样简单:

final useFields = ["id","created","subject","status","priority"] def input = [created:"16-Feb-2017", id:1234, priority:"low", status:"Foo", subject:"Bar"] println input def output = [:] useFields.each { output[it] = input[it] } // or this one-liner: // def output = useFields.inject([:]) { out, key -> out[key] = input[key]; out } println output

The standard Java class LinkedHashMap sorts map entries in the order they were added. And, as it turns out, the actual object created when you use the Groovy "map literal" syntax is, in fact, LinkedHashMap. So, getting the effect you want is as simple as creating an empty map literal and adding the entries from the existing map in the order desired:

final useFields = ["id","created","subject","status","priority"] def input = [created:"16-Feb-2017", id:1234, priority:"low", status:"Foo", subject:"Bar"] println input def output = [:] useFields.each { output[it] = input[it] } // or this one-liner: // def output = useFields.inject([:]) { out, key -> out[key] = input[key]; out } println output

更多推荐

本文发布于:2023-04-28 00:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   定义   Sort   Groovy   Order

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!