### Map For Each Loop

Various examples using the For .. Each Loop.
Note: The For To Loop should not be used - use For Each instead
Map with a String, Int, Boolean
'Create the map
Dim MyMap As Map = CreateMap("Key1":"Value1", "Key2":1, "Key3":True)
Log("List the Map Values using For .. Each")
For Each v As String In MyMap.Values
Log($"${v}"$)
Next
Log("List the Map Keys using For .. Each")
For Each k As String In MyMap.Keys
Log($"${k}"$)
Next
' Iterate over keys and values
For Each ItemNr As Int In MyMap.Keys
Dim Item As String = MyMap.Get(ItemNr)
Log($"Item number: ${ItemNr}, value: ${Item}"$)
Next
Note:
The For To Loop should not be used - use For Each instead
Example listing the Key = Value pair using For To Loop
Log("List the Map Key and Values using For .. To")
For i = 0 To MyMap.Size - 1
Log($"${MyMap.GetKeyAt(i)} = ${MyMap.GetValueAt(i)}"$)
Next
Map with Types
`Sub Process_Globals
...
'Define the Contact Type
Type ContactType (Id As Int, Name As String, EMail As String)
'Define the contact map. Each entry is ID = ContactType
Private ContactMap As Map
...
End Sub`
'Build the ContactMap holding ContactTypes
'Each Mapentry has as Key an Int and as Value a ContactType
`Sub BuildMap
ContactMap.Initialize
'Add some entries to the map
For i = 0 To 2
Dim Contact As ContactType
Contact.Initialize
Contact.Id = i
Contact.Name = "Name " & i
Contact.EMail = "email" & i & "@address.xyz"
'ID = ContactType
ContactMap.Put(i, Contact)
Next
End Sub`
'List the content of the ContactType
'Each Mapentry has as Key an Int and as Value a ContactType
'In the for each loop use the map values to get the contacts as contacttype
`Sub ListMap
For Each m As ContactType In ContactMap.Values
Log($"${m.Name} ${m.EMail} "$)
Next
End Sub`
Inline Java For Loop (requires JavaObject library)
`Sub Process_Globals
...
Private joMap As JavaObject = Me
...
End Sub`
`Sub MapForEachInlineJava
Dim MyMap As Map = CreateMap("Key1":"Value1", "Key2":"1", "Key3":"True")
joMap.RunMethod("LoopMap", Array(MyMap))
End Sub`
#If Java
import java.util.Map;
import java.util.Map.Entry;
//Looping over a map which has strings as values
public static void LoopMap(Map map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " , Value : " + entry.getValue());
}
}
#End If

Changed: 2018-05-26 17:17, Category: Map, File: T6C217M1597.htm, ID: 1597