Android Question Sort a List of Maps by key value of the maps

smercan

Member
Licensed User
Longtime User
I have a list filled with same type of maps.
Need to sort list by the any key value of maps.

I was trying to write a function for this and this sample code is working but I'am curious about that is there another way more simple or fast?

B4X:
public Sub SortMapListByKeyValue(mapList As List, keyName As String, ascending As Boolean) As List
  
    Dim keyValList As List
    keyValList.Initialize
  
    For Each m As Map In mapList
        keyValList.Add(m.Get(keyName))
    Next
  
    keyValList.Sort(ascending)
  
    Dim newList As List
    newList.Initialize
  
    For i=0 To keyValList.Size-1
        For j=0 To mapList.Size-1
            Dim m As Map = mapList.Get(j)
            If m.Get(keyName)=keyValList.Get(i) Then
                newList.Add(m)
                mapList.RemoveAt(j)
                Exit
            End If
        Next
    Next
  
    Return newList
End Sub
 

stevel05

Expert
Licensed User
Longtime User
How many keys in each map?
 
Upvote 0

smercan

Member
Licensed User
Longtime User
Count of map keys is not important I thought, the important thing that all maps must have the same parameter key
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
No, but if there aren't too many you could use a Type and the SortType function of list.
 
Upvote 0

smercan

Member
Licensed User
Longtime User
You are right. I get a json list from httpJob. My laziness came first before to write a Type, convert all of them into new list and finally sort
 
Upvote 0

smercan

Member
Licensed User
Longtime User
I am interested in this; I'll use a loop for the each map of list item to convert to a user-defined type, and I'll sort the resulting list. Will not it be longer than the direct sorting maps?
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…