user4541912
user4541912

Reputation:

Data structure to count frequency of equal items

I need to have data structure like HashSet.

  1. It should not add the same item into the collection
  2. But instead of adding the same item, it should count times this item was added.

As I understand HashSet calculates hashCode at first, if hashCode is the same it checks equals method if true than it will not add an item, otherwise item with the same hashCode but another equals will be added to the bucket linked list.

What I need to do is just keep only unique objects like Set does, but using equals method only, and if objects are equal than increment counter associated with each object.

Is there any such data structure already implemented, or I should create my own ?

Upvotes: 1

Views: 1168

Answers (2)

M A
M A

Reputation: 72854

The simplest way (without dependecies) is to have a HashMap<Element, Integer>. Or you can use Guava's MultiSet which has a count(Object) method to get the number of occurrences of an object in the collection.

Upvotes: 1

borjab
borjab

Reputation: 11655

It seems that what you really need is a map. For every item you can have the number of items

public class ItemCounter<T>{

    private Map<T, Integer> counts = new HashMap<T, Integer>();

    public void addItem(T item){
        Integer numberOfOcurrences = counts.get( item );            
        numberOfOcurrences = numberOfOcurrences == null ? 0 : numberOfOcurrences+1;
        counts.put( item,  numberOfOcurrences);            
    }

    public Integer getCount( T item ){
        Integer numberOfOcurrences = counts.get( item );    
        return numberOfOcurrences == null ? 0 : numberOfOcurrences;
    }
}

Upvotes: 3

Related Questions