Reputation: 497
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"]
Upvotes: 0
Views: 2896
Reputation: 3256
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
Upvotes: 1