Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of unique items in an ArrayList

Tags:

excel

vba

Is there a way to count the number of unique instances of items in an ArrayList without iterating through the entire list? Here is my code, and I would like to count the number of instances of Orange without iterating through the entire list - I am hoping there is a method to do it? In practice, the actual ArrayList will have hundreds of thousands of items.

Private Sub TestArrayList2()

    Dim TestAR As Object
    Dim Count As Integer

    Set TestAR = CreateObject("System.Collections.ArrayList")

    TestAR.Add "Apple"
    TestAR.Add "Orange"
    TestAR.Add "Orange"
    TestAR.Add "Orange"
    TestAR.Add "Pear"

    Count = TestAR.Count

End Sub
like image 556
mediaeval Avatar asked Dec 31 '22 16:12

mediaeval


1 Answers

I can't find a built in single function, but once the array list is sorted it's a simple case of locating the first (.IndexOf) and last (.lastIndexOf) occurrence of the string you're looking for:

lookingfor = "Orange"
TestAR.Sort
occurrences = TestAR.lastIndexOf(lookingfor) - TestAR.IndexOf(lookingfor, 0) + 1
like image 144
CLR Avatar answered Feb 24 '23 17:02

CLR