Looks like you're using wrong collection in first place - instead of Multimap you should use Multiset. From Guava Wiki:
Guava provides a new collection type, Multiset, which supports adding
multiples of elements. Wikipedia defines a multiset, in mathematics,
as “a generalization of the notion of set in which members are allowed
to appear more than once...In multisets, as in sets and in contrast to
tuples, the order of elements is irrelevant: The multisets {a, a, b}
and {a, b, a} are equal.”
There are two main ways of looking at this:
- This is like an
ArrayList<E> without an ordering constraint: ordering does not matter.
- This is like a
Map<E, Integer>, with elements and counts.
With Multiset your example will be:
Multiset<String> bag = HashMultiset.create();
bag.add("key1", 15);
bag.add("key2", 12);
bag.add("key1", 20);
And then bag will contain 35 occurences of "key1" and 12 occurences of "key2", i.e. bag.toString() will be { key1 x 35, key2 x 12 }. (Use LinkedHashMultiset if you want preserve order of keys).