Android Question Remove duplicate value list

Status
Not open for further replies.

Blue.Sky

Active Member
Licensed User
Longtime User
Hi
In list exist many duplicate value
example
[book,cd,dvd,book,cd]
How remove duplicate value from list?
 

eurojam

Well-Known Member
Licensed User
Longtime User
you can use a map for example, something like this (may be there are better or more efficient solutions;-)
B4X:
    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)
 
Upvote 0

Blue.Sky

Active Member
Licensed User
Longtime User
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
Best solution.
I use insertat but your way is correct
Do you can answer below topic?
https://b4x.com/android/forum/threads/use-java-listener-edittext.61913/
 
Upvote 0

wonder

Expert
Licensed User
Longtime User
Upvote 0

abdipn9984

Member
Licensed User
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
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
please give me an explanation, how to use this code
B4X:
    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

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
 
Upvote 0
Status
Not open for further replies.
Top