Serh.kry's blog

By Serh.kry, 9 years ago, In English

What to do in such case? Some time ago I've been solving the problem, which could be a trouble for me if all the values wasn't different.

  • Vote: I like it
  • +8
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I usually write my own class or methods for this.

For example, if you need a MuliSet I use a Map<?, Integer> to represent how many times a key is in the set, for a MultiMap you can use a Map<?, List<?>> to store all the values.

»
9 years ago, # |
  Vote: I like it +10 Vote: I do not like it

As for me, I usually just write my own class extending java.util.TreeMap

Counterquestion: why on earth you would need multimap?

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You can use this

    static class MultiSet <T> extends HashMap/*Change to TreeMap if you want */<T,Integer>
    {
	public void add(T key)
	{
	    Integer q = super.get(key);
	    if(q == null)
		super.put(key, 1);
	    else
		super.put(key, q+1);
	}
	@Override
	public Integer remove(Object key) {
	    Integer q = super.get(key);
	    if(q != null)
	    {
		if(q == 1)
		    super.remove(key);
		else
		    super.put((T)key, q-1);
	    }
	    else
		throw new NullPointerException("The specified key does not exist");

	    return q;
	}
    }