Android Code Snippet Convert data map to list

B4X:
'Convert a map into a list
'if KeyList=True, then return a list of keys, otherwise a list of values
public Sub MapToList(myMap As Map, KeyList As Boolean) As List
    Dim lst As List
    lst.Initialize
    If KeyList Then
        For Each item As Object In myMap.Keys
            lst.Add(item)
        Next
    Else
        For Each item As Object In myMap.Values
            lst.Add(item)
        Next
    End If
        
    Return lst
End Sub

test code:
    Dim mapWeekdays As Map=CreateMap("Sunday": 1, "Monday":2, "Tuesday":3, "Wednesday":4, "Thursday":5, "Friday":6, "Saturday":7)
    Dim lstValue As List=MapToList(mapWeekdays, False)
   log("value list:")
    For Each item As String In lstValue
        Log(item)
    Next
    Dim lstKey As List=MapToList(mapWeekdays, True)
   log("key list:")
    For Each item As String In lstKey
        Log(item)
    Next

value list:
1
2
3
4
5
6
7
key list:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
 

Sandman

Expert
Licensed User
Longtime User
Not at my computer at the moment, but curious if this also would work?
B4X:
'Convert a map into a list
'if KeyList=True, then return a list of keys, otherwise a list of values
public Sub MapToList(myMap As Map, KeyList As Boolean) As List
    
    If KeyList Then Return myMap.Keys.As(List)

    Return myMap.Values.As(List)

End Sub
 

toby

Well-Known Member
Licensed User
Longtime User
B4X:
'Convert a map into a list
'if KeyList=True, then return a list of keys, otherwise a list of values
public Sub MapToList(myMap As Map, KeyList As Boolean) As List
  
    If KeyList Then Return myMap.Keys.As(List)

    Return myMap.Values.As(List)

End Sub
I tried earlier and got the following error when trying to go throught the list:
java.lang.ClassCastException: anywheresoftware.b4a.objects.collections.Map$1 cannot be cast to java.util.List
 
Top