Dim List1 As List
List1.Initialize
List1.AddAll(Array As String("book","cd","dvd","book","cd"))
Dim m As Map
m.Initialize
For i = 0 To List1.Size-1
m.Put(List1.Get(i), List1.Get(i))
Next
List1.Clear
For Each v As String In m.Values
List1.Add(v)
Next
Log(List1)
Sub RemoveDuplicates(pList As List) As List
If pList = Null OR Not(pList.IsInitialized) Then Return pList
Dim lstNew As List : lstNew.Initialize
Dim objItem As Object
For i = 0 To pList.Size - 1
objItem = pList.Get(i)
If lstNew.IndexOf(objItem) = - 1 Then
lstNew.Add(objItem)
End If
Next
Return lstNew
End Sub
Best solution.B4X:Sub RemoveDuplicates(pList As List) As List If pList = Null OR Not(pList.IsInitialized) Then Return pList Dim lstNew As List : lstNew.Initialize Dim objItem As Object For i = 0 To pList.Size - 1 objItem = pList.Get(i) If lstNew.IndexOf(objItem) = - 1 Then lstNew.Add(objItem) End If Next Return lstNew End Sub
That's my choice as well!If you read the data from a database you could filter the duplicate entries directly in the query with:
SELECT DISTINCT
B4X:Sub RemoveDuplicates(pList As List) As List If pList = Null OR Not(pList.IsInitialized) Then Return pList Dim lstNew As List : lstNew.Initialize Dim objItem As Object For i = 0 To pList.Size - 1 objItem = pList.Get(i) If lstNew.IndexOf(objItem) = - 1 Then lstNew.Add(objItem) End If Next Return lstNew End Sub
please give me an explanation, how to use this code
Dim lstValues As List
lstValues.Initialize
For i = 1 To 10
lstValues.Add(i)
Next
For i = 3 To 5 ' adds 3 duplicated numbers, 3 to 5
lstValues.Add(i)
Next
Log("List before removing duplicates")
For i = 0 To lstValues.Size - 1
Log(lstValues.Get(i))
Next
lstValues = RemoveDuplicates(lstValues)
Log("List after removing duplicates")
For i = 0 To lstValues.Size - 1
Log(lstValues.Get(i))
Next
Sub RemoveDuplicates(pList As List) As List
If pList = Null Or Not(pList.IsInitialized) Then Return pList
Dim lstNew As List : lstNew.Initialize
Dim objItem As Object
For i = 0 To pList.Size - 1
objItem = pList.Get(i)
If lstNew.IndexOf(objItem) = - 1 Then
lstNew.Add(objItem)
End If
Next
Return lstNew
End Sub