Count the occurrences of items in ArrayList

后端 未结 6 828
长发绾君心
长发绾君心 2020-12-19 13:18

I have a java.util.ArrayList and an Item object.

Now, I want to obtain the number of times the Item is stored in t

6条回答
  •  梦毁少年i
    2020-12-19 13:52

    You can use Collections class:

    public static int frequency(Collection c, Object o)
    

    Returns the number of elements in the specified collection equal to the specified object. More formally, returns the number of elements e in the collection such that (o == null ? e == null : o.equals(e)).

    If you need to count occurencies of a long list many times I suggest you to use an HashMap to store the counters and update them while you insert new items to the list. This would avoid calculating any kind of counters.. but of course you won't have indices.

    HashMap counters = new HashMap(5000);
    ArrayList items = new ArrayList(5000);
    
    void insert(Item newEl)
    {
       if (counters.contains(newEl))
         counters.put(newEl, counters.get(newEl)+1);
       else
         counters.put(newEl, 1);
    
       items.add(newEl);
     }
    

    A final hint: you can use other collections framework (like Apache Collections) and use a Bag datastructure that is described as

    Defines a collection that counts the number of times an object appears in the collection.

    So exactly what you need..

提交回复
热议问题