Sub Activity_Create(FirstTime As Boolean)
Dim m As Map
m.Initialize
m.Put("aaa", 3)
m.Put("abc", 2)
m.Put("d", 3)
m.Put("ewr", 23)
SortMap(m)
End Sub
Sub SortMap(m As Map)
Dim list1 As List
list1.Initialize
Dim m2 As Map
m2.Initialize
For i = 0 To m.Size - 1
Dim word As String
Dim count As Int
word = m.GetKeyAt(i)
count = m.GetValueAt(i)
Dim l As List
l = m2.Get(count)
If l.IsInitialized = False Then
l.Initialize
m2.Put(count, l)
list1.Add(count)
End If
l.Add(word)
Next
list1.Sort(False) 'set to true for ascending sort.
'print the sorted values:
For i = 0 To list1.Size - 1
Dim count As Int
count = list1.Get(i)
Dim l As List
l = m2.Get(count)
For c = 0 To l.Size - 1
Log("Count = " & count & ", word = " & l.Get(c))
Next
Next
End Sub
This code is now obsolete.
Instead you should:
- Define a custom type with two values that will hold the key and value
- Create a list and add all the pairs.
- Use List.SortType to sort the list based on the required field.
One option is to use a small SQL table.
Another option is with this code:
B4X:Sub Activity_Create(FirstTime As Boolean) Dim m As Map m.Initialize m.Put("aaa", 3) m.Put("abc", 2) m.Put("d", 3) m.Put("ewr", 23) SortMap(m) End Sub Sub SortMap(m As Map) Dim list1 As List list1.Initialize Dim m2 As Map m2.Initialize For i = 0 To m.Size - 1 Dim word As String Dim count As Int word = m.GetKeyAt(i) count = m.GetValueAt(i) Dim l As List l = m2.Get(count) If l.IsInitialized = False Then l.Initialize m2.Put(count, l) list1.Add(count) End If l.Add(word) Next list1.Sort(False) 'set to true for ascending sort. 'print the sorted values: For i = 0 To list1.Size - 1 Dim count As Int count = list1.Get(i) Dim l As List l = m2.Get(count) For c = 0 To l.Size - 1 Log("Count = " & count & ", word = " & l.Get(c)) Next Next End Sub
Erel thanks for this code!
I have the opposite need How to sort the map keys ?
I expected that the map object has a sort method like the list object but I cannot find it within the map.
Sub SortMapKeys (m As Map, SortAsc As Boolean)
Private KeysList As List:KeysList.Initialize
Private m2 As Map:m2.Initialize
For i = 0 To m.Size - 1
Private key As String = m.GetKeyAt(i)
KeysList.Add(key)
Next
KeysList.Sort(SortAsc)
For x=0 To KeysList.Size - 1
Private key As String = KeysList.Get(x)
Private val As String = m.Get(key)
m2.Put(key, val)
Next
m.Clear
For Each m2Key As String In m2.Keys
m.Put(m2Key, m2.Get(m2Key))
Next
End Sub
Private val As Object = m.Get(key)