Sort a Map Alphabetically?

Monkey Forums/Monkey Programming/Sort a Map Alphabetically?

CopperCircle(Posted 2013) [#1]
Hi, I have a Map of a data class that has a multi-dimensional array.
I need to sort each key of the Map alphabetically, by fieldName[44][1]?

Global RenderDataList:StringMap<TemplateData>

Class TemplateData
Field fieldName:String[50][]
Field blah blah
End Class

Thanks.


muddy_shoes(Posted 2013) [#2]
That defines a Map of String->TemplateData. Do you mean that you'll set the string key to be fieldName[44][1]?

Monkey Maps use the "natural ordering" of the primitive types. If you just list the string keys via Keys() they'll be in alphabetical order, although there's nothing about this that's guaranteed.


CopperCircle(Posted 2013) [#3]
My map key is just an int that represents the data ID, I need to re-order the keys using the Data value of fieldName[44][1] in each key, in alphabetical order?

I guess I will need to create a temp Map and then cycle through and do a compare on the fieldName[44][1] of each key to build a key order array? Then right out a new Map in order?

Function SortKeys:StringMap<TemplateData>(DataList:StringMap<TemplateData>)
	Local map:=New StringMap<TemplateData>()
	Local key:Int=1
	For Local d:=Eachin DataList.Values
		map.Add(key, d)
		key=key+1
	Next
	Return map
End Function



muddy_shoes(Posted 2013) [#4]
If your key is an Int then why have you created a StringMap?

You can't re-order the keys in a map. All a map is required to do is allow you to retrieve a data item via a key value. The order in which you would get the keys or the data items if you iterate over them is just down to the internal implementation.

I'm afraid I don't follow what your objective is here. Do you want a list of your id number keys ordered by the fieldName[44][1] value or do you actually want a list of the TemplateData objects in that order? Do you want to interrogate this ordered list a lot or just occasionally?


CopperCircle(Posted 2013) [#5]
I want a list of my id number keys ordered by the fieldName[44][1], it will be only interrogated occasionally, my key is an int as it comes form a another data source and I need it to stay as the ID for that integration.

It just want to draw the string fieldName[44][1] in alphabetical order and know the key order.

Thanks.


muddy_shoes(Posted 2013) [#6]
I suspect there are far more sensible ways of going about this but without understanding your setup I can't advise. The code below should give you enough to create the SortKeys function you have above. Another way to go about it would be to create two maps, one from the key to the TemplateData and one from the string field to the key, and populate them both at the same time.





CopperCircle(Posted 2013) [#7]
Thanks for your help.