Android Code Snippet AddToMap

LucaMs

Expert
Licensed User
Routine name: AddToMap

Description: Adds or updates items to a Map or creates and fills a new map.

Dependencies: None

Code:
B4X:
' Adds or updates items to a Map or creates and fills a new map.
' To create a new Map, pass Null for the ExistingMap parameter.
' KeyList and ValueList must be the same size.
Sub AddToMap(KeyList As List, ValueList As List, ExistingMap As Map) As Map
    Private mapResult As Map : mapResult.Initialize
   
    If ExistingMap.IsInitialized Then
        mapResult = ExistingMap
    End If
   
    For i = 0 To KeyList.Size - 1
        mapResult.Put(KeyList.Get(i), ValueList.Get(i))
    Next
   
    Return mapResult
End Sub

Example:
B4X:
Private MyMap As Map

' Creates a new map.
MyMap = AddToMap(Array As String("One", "Two", "Three"), Array As String("Une", "Deux", "Trois"), Null)
LogWriteMap(MyMap)

' Adds items to the map
MyMap = AddToMap(Array As String("Four", "Five", "Six"), Array As String("Quatre", "Cinq", "Six"), MyMap)
LogWriteMap(MyMap)

'__________________________________________

Sub LogWriteMap(MapToWrite As Map)
    Log(CRLF & "***  Map content:")
    For i = 0 To MapToWrite.Size -1
        Log(MapToWrite.GetKeyAt(i) & " : " & MapToWrite.GetValueAt(i))
    Next
End Sub

Note: This arises because I envy the CreateMap B4J function. :D



Tags: Map, Collection, Array, List
 

LucaMs

Expert
Licensed User
Now I understand why this snippet was not appreciated.

I was going to add a long post about the usefulness of the Map, assuming that this was one of the reasons.

(I'm thinking of opening a thread to show how the Map Type is useful and powerful)



This snippet will be useful to the poor like me who do not have B4A v3.80 :D
 

Beja

Expert
Licensed User
Still your code is useful..
can you post a small project?!!
 

LucaMs

Expert
Licensed User
Still your code is useful..
can you post a small project?!!

you could simply create a new project and almost paste the example:

adding the two routines (AddToMap e LogWriteMap) to the Main actvitiy (better in a utilities code module);
declaring "Private MyMap AsMap" in the Globals
and
B4X:
' Creates a new map.
MyMap = AddToMap(Array As String("One", "Two", "Three"), Array As String("Une", "Deux", "Trois"), Null)
LogWriteMap(MyMap)

' Adds items to the map
MyMap = AddToMap(Array As String("Four", "Five", "Six"), Array As String("Quatre", "Cinq", "Six"), MyMap)
LogWriteMap(MyMap)
in a click event of some button or in Activity_Create - If firsttime...
 
Top