You basically need a Map
(preferably hash based), and an SortedSet
(probably a TreeSet
).
Map<Key,Value> byKey
and Set<Key> byValue
The first map will have the natural key's Comparator, while the second one will have a Comparator that first uses byKey.get(key1).compareTo(byKey.get(key2))
first, and only if they are deemed as equal, uses the natural Key
Comparator.
Add:
- check if element already exists, if it is - take it out from
byValue
. - modify the value in
byKey
- Add the element to byValue
Note that this ensures that the Set
is ordered by increasing value of the given values.
Assuming the map is hashed based, and every operation in it is O(1) on average, it gives you O(logn)
running time (removing from byValue
and adding to it).